问题:解释如何使用 Python 中的 split() 函数,根据指定的分隔符将字符串分割成子串。举例说明其用法。

解决方案: 在 Python 中,split() 函数用于根据指定的定界符将一个字符串拆分成子串。结果是一个子串列表。下面是 split() 函数的使用方法:

# Basic usage of split()
text = "Hello, World!"
words = text.split() # split by whitespace
print (words) #["He11o, ", "World!"]

使用 split() 函数

# Using a custom delimiter
date = "2023-10-08"
parts = date.split('-') # Split by hyphen
print(parts) # ['2023','10','08']

使用 split() 函数

# Limiting the number of splits
text = "apple, banana, cherry, date, fig"
fruits = text.split(',', 2) # Split by comma, maximum of 2 splits
print(fruits) # ['apple', 'banana', 'cherry, date, fig']

使用 split() 函数

# Splitting lines in a multiline string
multiline_text = "Line 1\nLine 2\nLine 3"
lines = multiline_text.splitlines()
print(lines) # ['Line 1', 'Line 2', 'Line 3']

使用 split() 函数