Reputation: 427
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?
Upvotes: 1
Views: 34666
Reputation: 11
text = "string,string,string:otherstring,otherstring,otherstring"
replace = text.replace(":", ",").split(",")
print(replace)
['string', 'string', 'string', 'otherstring', 'otherstring', 'otherstring']
Upvotes: 0
Reputation: 235984
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()
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']
Upvotes: 14
Reputation: 19264
Use a couple join()
statements to convert back to a string:
>>> string = "string,string,string:otherstring,otherstring,otherstring"
>>> ' '.join(' '.join(string.split(':')).split(',')).split()
['string', 'string', 'string', 'otherstring', 'otherstring', 'otherstring']
>>>
Upvotes: 2