Python - splitting a string twice
Question: I have some data that looks like
"string,string,string:otherstring,otherstring,otherstring".

I want to manipulate the first set of "string"s one at a time. If I split the
input and delimit it based off a colon, I will then end up with a list. I then
cannot split this again because "'list' object has no attribute 'split'".
Alternatively, if I decide to delimit based off a comma, then that will return
everything (including stuff after the comma, which I don't want to
manipulate). rsplit has the same problem. Now even with a list, I could still
manipulate the first entries by using [0], [1] etc. except for the fact that
the number of "string"s is always changing, so I am not able to hardcode the
numbers in place. Any ideas on how to get around this list limitation?


Answer: Try this:

    
    
    import re
    
    s = 'string,string,string:otherstring,otherstring,otherstring'
    re.split(r'[,:]', s)
    => ['string', 'string', 'string', 'otherstring', 'otherstring', 'other string']
    

We're using regular expressions and the
[`split()`](https://docs.python.org/2/library/re.html#re.split) method for
splitting a string with more than one delimiter. Or if you want to manipulate
the first group of strings in a separate way from the second group, we can
create two lists, each one with the strings in each group:

    
    
    [x.split(',') for x in s.split(':')]
    => [['string', 'string', 'string'], ['otherstring', 'otherstring', 'otherstring']]
    

… Or if you just want to retrieve the strings in the first group, simply do
this:

    
    
    s.split(':')[0].split(',')
    => ['string', 'string', 'string']
    

