Slobodan Stevic
Slobodan Stevic

Reputation: 348

Create a list from string, in Python 3.3

I have a string like this (with n number of elements):

input = 'John, 16, random_word, 1, 6, ...'

How can I convert it to a list like this? I would like ',' to be a separator.

output = [John, 16, random_word, 1, 6, ...]

Upvotes: 1

Views: 13164

Answers (4)

user1881957
user1881957

Reputation: 3378

Use the split function.

output = input.split(', ')

Upvotes: 1

Lev Levitsky
Lev Levitsky

Reputation: 65791

You can use input.split(',') but as others have noted, you'll have to deal with leading and trailing spaces. Possible solutions are:

  • without regex:

    In [1]: s = 'John, 16, random_word, 1, 6, ...'
    
    In [2]: [subs.strip() for subs in s.split(',')]
    Out[2]: ['John', '16', 'random_word', '1', '6', '...']
    

    What I did here is use a list comprehension, in which I created a list whose elements are made from the strings from s.split(',') by calling the strip method on them. This is equivalent to

    strings = []
    for subs in s.split(','):
        strings.append(subs)
    print(subs)
    
  • with regex:

    In [3]: import re
    
    In [4]: re.split(r',\s*', s)
    Out[4]: ['John', '16', 'random_word', '1', '6', '...']
    

Also, try not to use input as variable name, because you are thus shadowing the built-in function.

You can also just split on ', ', but you have to be absolutely sure there's always a space after the comma (think about linebreaks, etc.)

Upvotes: 6

nickanor
nickanor

Reputation: 669

you mean output = ['John', '16', 'random_word', '1', '6', ...]? you could just split it like output = inpt.split(', '). this also removes the whitespaces after ,.

Upvotes: 4

Matt
Matt

Reputation: 10823

If I understand correctly, simply do:

output = input.split(',')

You will probably need to trim each resulting string afterwards since split does not care about whitespaces.

Regards, Matt

Upvotes: 0

Related Questions