1

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?

1

3 Answers 3

14

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']
Sign up to request clarification or add additional context in comments.

3 Comments

Was going to post an answer with list-comps and chains, but this is much cleaner.
Thanks for the edit. I must not have explained myself well enough because the issue is that I don't need to process any of the strings after the comma (which is why I named the examples 'string' and 'otherstring'). However, your x.split idea will likely solve my problem now, as I'll just work with the content of the first "group". Thanks.
@Peter yup, the question wasn't clear. But now it is! see my last update, and that's it. Please don't forget to accept this answer ;)
2

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']
>>> 

Comments

0
text = "string,string,string:otherstring,otherstring,otherstring"
replace = text.replace(":", ",").split(",")
print(replace)

['string', 'string', 'string', 'otherstring', 'otherstring', 'otherstring']

Comments

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.