Python Split Function: Usage & Examples
In Python3, the split() function is a method used to separate a string based on a specified delimiter. The basic syntax of this function is as follows:
str.split(sep=None, maxsplit=-1)
Among them, the parameter ‘sep’ represents the delimiter, which defaults to None, indicating that white space such as a space or tab is used to split the string; the parameter ‘maxsplit’ represents the maximum number of splits, which defaults to -1, indicating splitting all substrings.
For example, let’s say we have a string like this:
str = "hello world"
If we want to divide a string using a space as a delimiter, we can use the split() method as follows:
result = str.split()
print(result)
The output is:
['hello', 'world']
In addition, we can also specify other delimiters, such as using a comma to separate strings.
str = "apple,orange,banana"
result = str.split(',')
print(result)
The output result is:
['apple', 'orange', 'banana']