Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 416
user63503 Avatar asked Nov 30 '10 01:11

user63503


People also ask

How do you split a string without spaces in Python?

Use the list() class to split a string into a list of strings. Use a list comprehension to split a string into a list of integers.

How do you split a string by any number of spaces in Python?

The Pythonic way of splitting on a string in Python uses the str. split(sep) function. It splits the string based on the specified delimiter sep . When the delimiter is not provided, the consecutive whitespace is treated as a separator.

How do you split a string into two spaces in Python?

You can use the Python string split() function to split a string (by a delimiter) into a list of strings. To split a string by space in Python, pass the space character " " as a delimiter to the split() function.


1 Answers

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'] 
like image 112
aaronasterling Avatar answered Sep 19 '22 21:09

aaronasterling