python用至少2个空格分割一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12866631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python split a string with at least 2 whitespaces
提问by Eagle
I would like to split a string only where there are at least two or more whitespaces.
我只想在至少有两个或更多空格的地方拆分字符串。
For example
例如
str = '10DEUTSCH GGS Neue Heide 25-27 Wahn-Heide -1 -1'
print str.split()
Results:
结果:
['10DEUTSCH', 'GGS', 'Neue', 'Heide', '25-27', 'Wahn-Heide', '-1', '-1']
I would like it to look like this:
我希望它看起来像这样:
['10DEUTSCH', 'GGS Neue Heide 25-27', 'Wahn-Heide', '-1', '-1']
采纳答案by unutbu
In [4]: import re
In [5]: text = '10DEUTSCH GGS Neue Heide 25-27 Wahn-Heide -1 -1'
In [7]: re.split(r'\s{2,}', text)
Out[7]: ['10DEUTSCH', 'GGS Neue Heide 25-27', 'Wahn-Heide', '-1', '-1']
回答by toxotes
As has been pointed out, stris not a good name for your string, so using wordsinstead:
正如已经指出的那样,str这不是您的字符串的好名字,因此请words改用:
output = [s.strip() for s in words.split(' ') if s]
The .split(' ') -- with two spaces -- will give you a list that includes empty strings, and items with trailing/leading whitespace. The list comprehension iterates through that list, keeps any non-blank items (if s), and .strip() takes care of any leading/trailing whitespace.
.split(' ') - 带有两个空格 - 将为您提供一个列表,其中包含空字符串和带有尾随/前导空格的项目。列表if s推导遍历该列表,保留所有非空白项 ( ),而 .strip() 处理任何前导/尾随空格。
回答by Ashwini Chaudhary
In [30]: strs='10DEUTSCH GGS Neue Heide 25-27 Wahn-Heide -1 -1'
In [38]: filter(None, strs.split(" "))
Out[38]: ['10DEUTSCH', 'GGS Neue Heide 25-27', ' Wahn-Heide', ' -1', '-1']
In [32]: map(str.strip, filter(None, strs.split(" ")))
Out[32]: ['10DEUTSCH', 'GGS Neue Heide 25-27', 'Wahn-Heide', '-1', '-1']
For python 3, wrap the result of filterand mapwith listto force iteration.
对于 python 3,将filter和mapwith的结果包装起来list以强制迭代。
回答by Jean-Fran?ois Fabre
In the case of:
如果是:
- mixed tabs and spaces
- blanks at start and/or at end of the string
- 混合制表符和空格
- 字符串开头和/或结尾的空格
(originally answering to Split string at whitespace longer than a single space and tab characters, Python)
(最初回答Split string at whitespace 长于单个空格和制表符,Python)
I would split with a regular expression: 2 or more blanks, then filter out the empty strings that re.splityields:
我会用正则表达式拆分:2 个或更多空格,然后过滤掉产生的空字符串re.split:
import re
s = ' 1. 1. 2. 1 \tNote#EvE\t \t1\t \tE3\t \t 64\t 1. 3. 2. 120 \n'
result = [x for x in re.split("\s{2,}",s) if x]
print(result)
prints:
印刷:
['1. 1. 2.', '1', 'Note#EvE', '1', 'E3', '64', '1. 3. 2. 120']
this isn't going to preserve leading/trailing spaces but it's close.
这不会保留前导/尾随空格,但它很接近。

