Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex separate space-delimited words into a list

If I have a string = "hello world sample text"

I want to be able to convert it to a list = ["hello", "world", "sample", "text"]

How can I do that with regular expressions? (other methods not using re are acceptable)

like image 846
Andrew Avatar asked Dec 08 '10 00:12

Andrew


People also ask

How do you split a string into a list by spaces?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string by the occurrences of a regex pattern Python?

split() works. The re. split() function splits the given string according to the occurrence of a particular character or pattern. Upon finding the pattern, this function returns the remaining characters from the string in a list.

How do you split words in regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

How do you split text by space comma delimiter 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 comma in Python, pass the comma character "," as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of "," .


1 Answers

"hello world sample text".split()

will split on any whitespace. If you only want to split on spaces

"hello world sample text".split(" ")

regex version would be something like this

re.split(" +", "hello world sample text")

which works if you have multiple spaces between the words

like image 59
John La Rooy Avatar answered Sep 20 '22 16:09

John La Rooy