I'm trying to find the most pythonic way to split a string like
"some words in a string"
into single words. string.split(' ')
works ok but it returns a bunch of white space entries in the list. Of course i could iterate the list and remove the white spaces but I was wondering if there was a better way?
The standard solution to split a string is using the split() method provided by the String class. It accepts a regular expression as a delimiter and returns a string array. To split on any whitespace character, you can use the predefined character class \s that represents a whitespace character.
Use the str. split() method without an argument to split a string by unknown number of spaces, e.g. my_list = my_str. split() .
Just use my_str.split()
without ' '
.
More, you can also indicate how many splits to perform by specifying the second parameter:
>>> ' 1 2 3 4 '.split(None, 2)
['1', '2', '3 4 ']
>>> ' 1 2 3 4 '.split(None, 1)
['1', '2 3 4 ']
How about:
re.split(r'\s+',string)
\s
is short for any whitespace. So \s+
is a contiguous whitespace.
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