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

Python

Python Problem Overview


I need a function similar to str.split(' ') but there might be more than one space, and different number of them between the meaningful characters. Something like this:

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

Can I somehow use regular expressions to catch those spaces in between?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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 - Python

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)

Solution 4 - Python

To split lines by multiple spaces while keeping single spaces in strings:

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

Solution 5 - Python

We can also use regex's split method here too.

import re

sample = ' 1234    Q-24 2010-11-29         563   abc  a6G47er15        '

word_list = re.split("\s+", sample.strip())

print(word_list) #['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15']

I hope this might help someone

Solution 6 - Python

There are many solutions to this question.

1.) Using split() is the simplest method

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.) There is another way to solve this using findall() method, you need to "import re" in the starting of your python file.

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.) If you want to remove any leading (spaces at the beginning) and trailing (spaces at the end) alone use strip().

s = '   hello          '
output = s.strip()
print(output)


Output >> hello

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser63503View Question on Stackoverflow
Solution 1 - PythonaaronasterlingView Answer on Stackoverflow
Solution 2 - PythonBill LynchView Answer on Stackoverflow
Solution 3 - PythonDanny SanchezView Answer on Stackoverflow
Solution 4 - PythonGuy de CarufelView Answer on Stackoverflow
Solution 5 - Pythonhitesh bedreView Answer on Stackoverflow
Solution 6 - PythonMuthu KumarView Answer on Stackoverflow