Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string by arbitrary number of white spaces

Tags:

python

split

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?

like image 340
jonathan topf Avatar asked Oct 23 '12 10:10

jonathan topf


People also ask

How do you split a string in white spaces?

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.

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

Use the str. split() method without an argument to split a string by unknown number of spaces, e.g. my_list = my_str. split() .


2 Answers

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  ']
like image 172
K Z Avatar answered Oct 05 '22 06:10

K Z


How about:

re.split(r'\s+',string)

\s is short for any whitespace. So \s+ is a contiguous whitespace.

like image 42
codaddict Avatar answered Oct 05 '22 06:10

codaddict