[英]python 2.7 - how to turn a string into a list when seperators are digits and '\\n'
for example i have the string : 例如我有字符串:
"hello0there\\nhow3are6you1today?"
what i want to get is : 我想要得到的是:
["hello", "there", "how", "are", "you", "today?"]
the digits represent spaces, and the \\\\n
is a new line. 数字代表空格,
\\\\n
是换行。 i've tried split()
to do it but it can only get 2 arguements and not more, so it's not optinal. 我已经尝试过
split()
来做到这一点,但是它只能得到2个论点,而不能更多,因此它不是最佳的。
i also found this : 我也发现了这个:
filter(None, re.split("['1234567890']+", string_to_split))
which works fine for the digits, yet not for the '\\\\n'
. 它适用于数字,但不适用于
'\\\\n'
。 is there any way to split the string by the digits and the '\\\\n'
in one action? 有什么办法可以一次将数字和
'\\\\n'
分开的字符串?
i cant figure out a way to split it in two separated functions because once I've created a list i cannot split it again. 我想不出一种将其拆分为两个单独功能的方法,因为一旦创建了列表,便无法再次拆分。
if anyone knows of a way to do so, please help me. 如果有人知道这样做的方法,请帮助我。 thanks
谢谢
You need to add \\s
and \\\\n
to your regex : 您需要在正则表达式中添加
\\s
和\\\\n
:
>>> s="hello0there\\nhow3are6you1today?"
>>> re.split(r'[\d\s\\n]*',s)
['hello', 'there', 'how', 'are', 'you', 'today?']
For getting ride of splitting with n
's in your strings you can use a positive look behind and and an logical or : 为了获得在字符串中使用
n
进行拆分的方法,您可以在后面加上正向外观,并使用逻辑或:
>>> re.split(r'[\d\s\\]|(?<=\\)n',s)
But since it might produce an empty string you can use a list comprehension to get ride of that. 但是因为它可能会产生一个空字符串,所以您可以使用列表推导来理解。
>>> [i for i in re.split(r'[\d\s\\]|(?<=\\)n',s) if i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.