【发布时间】:2012-10-23 10:09:47
【问题描述】:
我正在尝试找到最 Pythonic 的方式来拆分字符串,例如
“字符串中的一些单词”
成单个单词。 string.split(' ') 工作正常,但它会在列表中返回一堆空白条目。当然我可以迭代列表并删除空格,但我想知道是否有更好的方法?
【问题讨论】:
我正在尝试找到最 Pythonic 的方式来拆分字符串,例如
“字符串中的一些单词”
成单个单词。 string.split(' ') 工作正常,但它会在列表中返回一堆空白条目。当然我可以迭代列表并删除空格,但我想知道是否有更好的方法?
【问题讨论】:
只需使用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 ']
【讨论】:
怎么样:
re.split(r'\s+',string)
\s 是任何空格的缩写。所以\s+ 是一个连续的空白。
【讨论】:
使用不带参数的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分隔符拆分空字符串或仅包含空格的字符串将返回[]。
【讨论】:
>>> 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', '', '', '', '', '']
或者它只会用一个空格来分割一个
【讨论】:
最Pythonic和正确的方法是不指定任何分隔符:
"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?
【讨论】:
text = "".join([w and w+" " for w in text.split(" ")])
将大空格转换为单个空格
【讨论】: