-2

Given the string

string1='apple purple orange brown'

How would I go about turning it into a list

list1=['apple','purple','orange','brown']

I thought I could do

string1='apple purple orange brown'
list1=[]
for item in string1:
     list1.append(item)

But that gives me a list of every single character of the string, not just the words. Would there be a way to split the string up by it's spaces, and then add it to the list?

Bob
  • 1,344
  • 3
  • 29
  • 63

3 Answers3

1

Use the split() method on String. It gives you a list:

>>> "Foo bar".split()
['Foo', 'bar']

If you want to split on something else than whitespace, just pass it to split:

>>> "Pipe|separated|values".split("|")
['Pipe', 'separated', 'values']

Split knows even more tricks, like limiting the amount of splits.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
0
string1='apple purple orange brown'
list1=[]
list1.extend(string1.split(' '))

leaves

list1 == ['apple', 'purple', 'orange', 'brown']

The expression string1.split(' ') is itself a list of just the substrings that were separated by spaces, but you can use extend to add the result onto an existing list if you might have other content on that list.


If you need to deal with human language sentences, not just single spaces between words, then you might want to look into proper text segmentation as discussed at https://stackoverflow.com/a/7188852/20394

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
0
string1='apple purple orange brown'
list1=string1.split()

Your list is in list1

Edit: The split function return a list

Nicolas HENAUX
  • 1,656
  • 1
  • 14
  • 18