我有串,其中包括例如一些无关痛痒的文字 :如何分割具有多个分隔符的Python字符串?
"t1, t2, t3"
如果我分裂它通过split(",")
方法我得到一个列表,其中第二项和第三项还包括空白。
如何拆分所需的字符串与乘法分隔符?
我有串,其中包括例如一些无关痛痒的文字 :如何分割具有多个分隔符的Python字符串?
"t1, t2, t3"
如果我分裂它通过split(",")
方法我得到一个列表,其中第二项和第三项还包括空白。
如何拆分所需的字符串与乘法分隔符?
如果您不需要空格,你可以使用:
"t1, t2, t3,t4".replace(" ", "").split(",")
如果逗号后有任意的空间,只是用一个列表理解剥离空白:
[t.strip() for t in inputstring.split(',')]
或使用正则表达式拆分(在这种情况下,有些矫枉过正):
import re
re.split(r',\s*', inputstring)
示范:
>>> inputstring = 't1, t2, t3,t4, t5'
>>> [t.strip() for t in inputstring.split(',')]
['t1', 't2', 't3', 't4', 't5']
>>> import re
>>> re.split(r',\s*', inputstring)
['t1', 't2', 't3', 't4', 't5']
要么将它们拆分", "
(注意空间)或strip
后话:
[e.strip() for e in "t1, t2, t3,t4".split(",")]
>>> ['t1', 't2', 't3', 't4']
使用带()。
s = "t1, t2, t3"
s = [x.strip() for x in s.split(",")]
print s
的可能重复[Python的:句子分裂产生一个空格(http://stackoverflow.com/questions/14307949/python -sentence-splitting-produce-a-whitespace) – Useless