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

时间:2012-05-22 07:38:34

标签: python regex string split

我对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 个答案:

答案 0 :(得分:10)

您可以简单地指定一些拆分:

s.split(' ', 4)

答案 1 :(得分:2)

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

 sp = s.split(' ', 4)

答案 2 :(得分: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']