python split 函数使用多个分隔符

2023-02-25 00:00:00 函数 多个 分隔符

在 Python 中,可以使用正则表达式模块 re 中的 re.split() 方法来实现多个分隔符的切分。具体来说,可以通过使用 | 运算符来表示多个分隔符,例如:

import re

string = "The quick brown fox|jumps,over the lazy dog"
words = re.split(r'[|, ]+', string)
print(words)  # ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

上述代码中,'[|, ]+' 表示匹配 |、, 或空格,+ 表示匹配至少一个。

也可以使用列表生成式或者 for 循环来实现多个分隔符的切分,例如:

string = "The quick brown fox|jumps,over the lazy dog"
separators = ['|', ',', ' ']
for sep in separators:
    string = string.replace(sep, '|')
words = string.split('|')
print(words)  # ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

上述代码中,首先将多个分隔符替换为一个统一的分隔符 |,然后使用 split 方法切分字符串。这种方法的缺点是需要修改原始字符串,可能会改变原有的语义,因此不适用于所有场景。

相关文章