1

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, ...]

4 Answers 4

6

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please explain the "without regex" steps a bit more in detail? I can't seem to replicate what you did. Please note that I've been learning programming for only a week or so. And thank you!
@SlobodanStevic I tried to outline the process, feel free to ask more specific questions. Note that what I showed was from an interactive ipython session, and if you try putting this in a script, you won't see any output unless you explicitly print something.
4

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

1 Comment

This seems to be exactly what I need, thanks! Considering that my string will always be formatted so that space only comes after the comma.
1

Use the split function.

output = input.split(', ')

Comments

0

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

1 Comment

Thanks! I didn't explain well, but you got it right. This does what I wanted, now just to remove those spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.