Andrew
Andrew

Reputation: 3999

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)

Upvotes: 8

Views: 14916

Answers (1)

John La Rooy
John La Rooy

Reputation: 304225

"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

Upvotes: 18

Related Questions