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?
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With