Python Split() Function: Usage & Examples

In Python, the split() function is used to split a string into multiple substrings based on a specified delimiter, and then return these substrings in a list. Its basic syntax is:

str.split(sep=None, maxsplit=-1)

The parameter `sep` is used to specify the separator, with a default value of None indicating that a space is used as the separator; the parameter `maxsplit` is used to specify the maximum number of splits, if set to a positive integer `n`, it will split up to `n` times, if set to a negative integer, it indicates an unlimited number of splits.

For example, the string “hello world” can be split into two substrings by using the split() function, dividing it by spaces.

s = "hello world"
result = s.split()
print(result)
# 输出: ['hello', 'world']

If you want to split the string using a different delimiter, you can specify that delimiter as a parameter in the split() function. For example, if you have a string “apple,orange,banana”, you can split it using a comma as the delimiter.

s = "apple,orange,banana"
result = s.split(',')
print(result)
# 输出: ['apple', 'orange', 'banana']
bannerAds