Python正则表达式split()字符串

2024-09-29 12:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python中的正则表达式很陌生。我有下面的字符串,想把它们分成五类。我只使用split(),但它将根据空格进行拆分。在

s = "1 0 A10B 1/00 Description: This is description with spaces"
sp = s.split()
>>> sp
["1", "0", "A10B", "1/00", "Description:", "This", "is", "description", "with", "spaces"]

如何编写正则表达式使其拆分为这样:

^{pr2}$

有人能帮忙吗?谢谢!在


Tags: 字符串iswithdescriptionthisspspacessplit
3条回答

您可以简单地指定多个拆分:

s.split(' ', 4)

split()的第二个参数是要执行的最大拆分数。如果将其设置为4,则剩余的字符串将是列表中的第5项。在

 sp = s.split(' ', 4)

不是一个完美的解决方案。但首先。在

>>> sp=s.split()[0:4]
>>> sp.append(' '.join(s.split()[4:]))
>>> print sp
['1', '0', 'A10B', '1/00', 'Description: This is description with spaces']

相关问题 更多 >