在Python中拆分一个空格数未知的字符串作为分隔符

在Python中拆分一个空格数未知的字符串作为分隔符,python,Python,我需要一个类似于str.split(“”)的函数,但可能有多个空格,并且有意义的字符之间的空格数不同。大概是这样的: s = ' 1234 Q-24 2010-11-29 563 abc a6G47er15 ' ss = s.magic_split() print(ss) # ['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15'] 我是否可以使用正则表达式捕获中间的空格?如果不将任何参数传递

我需要一个类似于
str.split(“”)
的函数,但可能有多个空格,并且有意义的字符之间的空格数不同。大概是这样的:

s = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15        '
ss = s.magic_split()
print(ss)  # ['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']

我是否可以使用正则表达式捕获中间的空格?

如果不将任何参数传递给,它会将空格的运行视为单个分隔符:

>>> ' 1234    Q-24 2010-11-29         563   abc  a6G47er15'.split()
['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']
或者如果你愿意的话

>>> class MagicString(str):
...     magic_split = str.split
... 
>>> s = MagicString(' 1234    Q-24 2010-11-29         563   abc  a6G47er15')
>>> s.magic_split()
['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']

如果数据中只有一个空格(如一个字段中的地址),那么当分隔符有两个或多个空格时,有一个解决方案:

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)

要在字符串中保留单个空格的同时按多个空格拆分行,请执行以下操作:

with open("textfile.txt") as f:
   for line in f:
      line = [i.strip() for i in line.split('  ') if i]
      print(line)

这个问题有很多解决办法

1.)使用split()是最简单的方法

s = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15              '
s = s.split()
print(s)


Output >> ['1234','Q-24','2010-11-29','563','abc','a6G47er15']
2.)使用findall()方法还有另一种解决方法,您需要在python文件的开头“导入re”

import re
def MagicString(str):
    return re.findall(r'\S+', str)
s = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15'
s = MagicString(s)
print(s)
print(MagicString('    he  ll   o'))


Output >> ['1234','Q-24','2010-11-29','563','abc','a6G47er15']
Output >> ['he','ll','o']
3.)如果要单独删除任何前导(开头的空格)和尾随(结尾的空格),请使用strip()


请注意,如果没有参数,split()会在“任意空格”上拆分,因此制表符(例如)也会被视为分隔符(并作为单个分隔符吸收到制表符空间序列中)。如果这确实是一个问题(几乎从来都不是),那么
[subs for subs in s.split(“”)If s]
如果字符串中一行有4个空格,您将在结果中得到一个空字符串。
import re
def MagicString(str):
    return re.findall(r'\S+', str)
s = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15'
s = MagicString(s)
print(s)
print(MagicString('    he  ll   o'))


Output >> ['1234','Q-24','2010-11-29','563','abc','a6G47er15']
Output >> ['he','ll','o']
s = '   hello          '
output = s.strip()
print(output)


Output >> hello