7

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)

Andrew
  • 3,901
  • 15
  • 50
  • 64

1 Answers1

18
"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

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Both of your solutions work if you have multiple spaces between words – Mike Axiak Dec 08 '10 at 00:35
  • 4
    @Mike, the behaviour of `str.split` is slightly different when the split string is specified as a space, multiple spaces will be split because they have empty string between them. – John La Rooy Dec 08 '10 at 00:47