Python正则表达式split()函数用于字符串分割。

4

我在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"]

如何编写正则表达式以使其分割成以下形式?
 ["1", "0", "A10B", "1/00", "Description: This is description with spaces"]
3个回答

10

您可以简单地指定要分割的次数:

s.split(' ', 4)

2
< p > split() 的第二个参数是要执行的最大分割次数。如果将此设置为 4,则剩余的字符串将成为列表中的第 5 项。

 sp = s.split(' ', 4)

1

不是完美的解决方案。但至少是一个开始。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接