我需要一个类似于string.split('')的函数,但可能有多个空格,并且有意义的字符之间有不同的数量.像这样的东西:
s = ' 1234 Q-24 2010-11-29 563 abc a6G47er15 '
ss = s.magicSplit()
print ss
['1234','Q-24','2010-11-29','563','abc','a6G47er15']
Run Code Online (Sandbox Code Playgroud)
我可以以某种方式使用正则表达式来捕捉它们之间的空格吗?
有人可以帮帮忙吗?
aar*_*ing 93
尝试
>>> ' 1234 Q-24 2010-11-29 563 abc a6G47er15'.split()
['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']
Run Code Online (Sandbox Code Playgroud)
或者如果你想
>>> class MagicString(str):
... magicSplit = str.split
...
>>> s = MagicString(' 1234 Q-24 2010-11-29 563 abc a6G47er15')
>>> s.magicSplit()
['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']
Run Code Online (Sandbox Code Playgroud)
Bil*_*nch 20
s = ' 1234 Q-24 2010-11-29 563 abc a6G47er15 '
ss = s.split()
print ss
['1234','Q-24','2010-11-29','563','abc','a6G47er15']
Run Code Online (Sandbox Code Playgroud)
如果您的数据中有单个空格(例如一个字段中的地址),那么当分隔符有两个或多个空格时,这里有一个解决方案:
with open("textfile.txt") as f:
content = f.readlines()
for line in content:
# Get all variable-length spaces down to two. Then use two spaces as the delimiter.
while line.replace(" ", " ") != line:
line = line.replace(" ", " ")
# The strip is optional here.
data = line.strip().split(" ")
print(data)
Run Code Online (Sandbox Code Playgroud)