python用至少2个空格分割一个字符串 [英] python split a string with at least 2 whitespaces
本文介绍了python用至少2个空格分割一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只想在至少有两个或更多空格的地方拆分字符串.
I would like to split a string only where there are at least two or more whitespaces.
例如
str = '10DEUTSCH GGS Neue Heide 25-27 Wahn-Heide -1 -1'
print str.split()
结果:
['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']
推荐答案
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']
更新 2021+ 答案.
str.split
现在接受要拆分的正则表达式.
在此处阅读更多信息
Update 2021+ answer.
str.split
now accepts regular expressions to split on.
read more here
row = '10DEUTSCH GGS Neue Heide 25-27 Wahn-Heide -1 -1'
df = pd.DataFrame({'string' : row},index=[0])
print(df)
string
0 10DEUTSCH GGS Neue Heide 25-27 Wahn...
df1 = df['string'].str.split('\s{2,}',expand=True)
print(df1)
0 1 2 3 4
0 10DEUTSCH GGS Neue Heide 25-27 Wahn-Heide -1 -1
这篇关于python用至少2个空格分割一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文