How is the split function used in Python?
In Python, the split() function is used to split a string based on a specified delimiter and return a list. The usage of the split() function is as follows:
string.split(separator, maxsplit)
Among them:
- The separator indicates the symbol used to divide a string. If the parameter is omitted, a space is used as the default separator.
- maxsplit: indicates the number of times to split, if this parameter is specified, the splitting will be done no more than maxsplit times. If this parameter is omitted or specified as -1, it means there is no limit on the number of splits.
Here are some examples:
# 使用空格作为分隔符
string = "Hello World"
result = string.split()
print(result) # 输出:['Hello', 'World']
# 使用逗号作为分隔符
string = "apple,banana,orange"
result = string.split(',')
print(result) # 输出:['apple', 'banana', 'orange']
# 指定分割次数
string = "Hello World"
result = string.split(' ', 1)
print(result) # 输出:['Hello', 'World']
Note: The split() function returns a list, where each element represents a portion that has been split. If the string cannot be split, the split() function will return a list containing the entire string.