Python字符串 |分裂()
Python中的split()方法在用指定的分隔字符串字符串后,将字符串拆分为字符串列表。
Syntax : str.split(separator, maxsplit)
Parameters :
separator : This is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator.
maxsplit : It is a number, which tells us to split the string into maximum of provided number of times. If it is not provided then the default is -1 that means there is no limit.
Returns : Returns a list of strings after breaking the given string by the specified separator.
示例 1:演示 split()函数如何工作的示例
text = 'geeks for geeks'
# Splits at space
print(text.split())
word = 'geeks, for, geeks'
# Splits at ','
print(word.split(','))
word = 'geeks:for:geeks'
# Splitting at ':'
print(word.split(':'))
word = 'CatBatSatFatOr'
# Splitting at t
print(word.split('t'))
输出 :
['geeks', 'for', 'geeks']
['geeks', ' for', ' geeks']
['geeks', 'for', 'geeks']
['Ca', 'Ba', 'Sa', 'Fa', 'Or']
示例 2:演示指定 maxsplit 时 split()函数如何工作的示例
word = 'geeks, for, geeks, pawan'
# maxsplit: 0
print(word.split(', ', 0))
# maxsplit: 4
print(word.split(', ', 4))
# maxsplit: 1
print(word.split(', ', 1))
输出 :
['geeks, for, geeks, pawan']
['geeks', 'for', 'geeks', 'pawan']
['geeks', 'for, geeks, pawan']