我正在尝试找到最像pythonic的方法来分割像
这样的字符串“字符串中的某些单词”
单词成语。string.split(' ')
正常工作,但它会在列表中返回一堆空白条目。当然我可以迭代列表并删除空格,但我想知道是否有更好的方法?
答案 0 :(得分:25)
只需使用my_str.split()
而不使用' '
。
此外,您还可以通过指定第二个参数来指示要执行的拆分数:
>>> ' 1 2 3 4 '.split(None, 2)
['1', '2', '3 4 ']
>>> ' 1 2 3 4 '.split(None, 1)
['1', '2 3 4 ']
答案 1 :(得分:11)
怎么样:
re.split(r'\s+',string)
\s
是任何空格的缩写。所以\s+
是一个连续的空格。
答案 2 :(得分:5)
使用不带参数的string.split()
或re.split(r'\s+', string)
代替:
>>> s = 'some words in a string with spaces'
>>> s.split()
['some', 'words', 'in', 'a', 'string', 'with', 'spaces']
>>> import re; re.split(r'\s+', s)
['some', 'words', 'in', 'a', 'string', 'with', 'spaces']
来自docs:
如果未指定
sep
或None
,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,结果在开始时不包含空字符串或如果字符串具有前导或尾随空格,则结束。因此,将空字符串或仅包含空格的字符串与None
分隔符分开将返回[]
。
答案 3 :(得分:1)
>>> a = "some words in a string"
>>> a.split(" ")
['some', 'words', 'in', 'a', 'string']
split参数不包含在结果中,所以我猜你的字符串更多。否则,它应该工作
如果你有多个空格,只需使用不带参数的split()
>>> a = "some words in a string "
>>> a.split()
['some', 'words', 'in', 'a', 'string']
>>> a.split(" ")
['some', 'words', 'in', 'a', 'string', '', '', '', '', '']
或者只是按单个空格分割
答案 4 :(得分:0)
text = "".join([w and w+" " for w in text.split(" ")])
将大空间转换为单个空格
答案 5 :(得分:0)
最Python化和正确的方法是不指定任何分隔符:
"some words in a string".split()
# => ['some', 'words', 'in', 'a', 'string']
又读: How can I split by 1 or more occurrences of a delimiter in Python?