Python example to 将字符串拆分为 列表 的标记 using the delimiters such as space, comma, 正则表达式, or multiple delimiters.
拆分方法的语法是:
string.split(separator, maxsplit)
默认情况下,拆分() 方法将字符串分成无限标记的列表,默认分隔符是任何空格。在以下示例中,字符串在单词之间包含非偶数空格
>>> str = 'how to do in java'
>>> str.split() # split string using default delimiter and max splits
['how', 'to', 'do', 'in', 'java'] #Output
在以下示例中,我们使用逗号作为分隔字符串的分隔符。
>>> str = 'how,to,do,in,java'
>>> str.split(',') # split string using delimiter comma
['how', 'to', 'do', 'in', 'java'] #Output
字符串对象的 拆分()
方法实际上适用于非常简单的情况,并且不允许使用多个定界符或考虑定界符周围可能存在的空格。
如果您需要更多灵活性,请使用 重新拆分()
方法:
>>> import re
>>> line = 'how to; do, in,java, dot, com'
>>> re.split(r'[;,\s]\s*', line) # split with delimiters comma, semicolon and space
# followed by any amount of extra whitespace.
['how', 'to', 'do', 'in', 'java', 'dot', 'com']
When using 重新拆分()
, we need to be a bit careful should the regular expression pattern involve a capture group enclosed in parentheses. 如果使用捕获组,则匹配的文本也会包含在结果中。
例如,看看这里发生了什么:
>>> import re
>>> line = 'how to; do, in,java, dot, com'
>>> re.split(r'(;|,|\s)\s*', line) # split with delimiters comma, semicolon and space
# followed by any amount of extra whitespace.
['how', ' ', 'to', ';', 'do', ',', 'in', ',', 'java', ',', 'dot', ',', 'com']
快乐学习!!
地址:https://www.cundage.com/article/split-string.html