如何使用 Python 根据多个分隔符拆分字符串?
pythonserver side programmingprogramming
问题
您需要将字符串拆分为字段,但分隔符在整个字符串中不一致。
解决方案
在 Python 中有多种方法可以拆分一个或多个具有多个分隔符的字符串。最简单、最简单的方法是使用 split() 方法,但它旨在处理简单情况。
在处理复杂字符串场景时,re.split() 比普通的 `split()` 方法更灵活。
使用 re.split(),您可以为分隔符指定多种模式。如解决方案所示,分隔符可以是连字符 (-),也可以是空格 ( ),或者是逗号 (,) 后跟的值。正则表达式文档可在此处找到。
只要找到该模式,整个匹配项就会成为匹配项两侧字段之间的分隔符。
仅提取分隔符之间的文本(无分隔符)。
示例
import re tennis_greats = 'Roger-federer, Rafael nadal, Novak Djokovic,Andy murray' """" #----------------------------------------------------------------------------- # Scenario 1 - Output the players # Input - String with multiple delimiters ( - , white space) # Code - Specify the delimters in [] #----------------------------------------------------------------------------- """ players = re.split(r'[-,\s]\s*',tennis_greats)
输出
print(f" The output is - {players}")
输出为 -
['Roger', 'federer', 'Rafael', 'nadal', 'Novak', 'Djokovic', 'Andy', 'murray']
连同分隔符一起提取分隔符之间的文本
示例
import re tennis_greats = 'Roger-federer, Rafael nadal, Novak Djokovic,Andy murray' """" #----------------------------------------------------------------------------- # Scenario 2 - Output the players and the delimiters # Input - String with multiple delimiters ( - , white space) # Code - Specify the delimters between pipe (|) #----------------------------------------------------------------------------- """ players = re.split(r'(-|,|\s)\s*',tennis_greats)
输出
print(f" The output is -{players}")
输出为 -
['Roger', '-', 'federer', ',', 'Rafael', ' ', 'nadal', ',', 'Novak', ' ', 'Djokovic', ',', 'Andy', ' ', 'murray']
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

