Split a string with unknown number of spaces as separator in Python

Solution 1:

If you don't pass any arguments to str.split(), it will treat runs of whitespace as a single separator:

>>> ' 1234    Q-24 2010-11-29         563   abc  a6G47er15'.split()
['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']

Or if you want

>>> 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']

Solution 2:

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

Solution 3:

If you have single spaces amid your data (like an address in one field), here's a solution for when the delimiter has two or more spaces:

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)