Reputation: 4263
I have a list of strings that all follow a format of parts of the name divided by underscores. Here is the format:
string="somethingX_somethingY_one_two"
What I want to know how to do it extract "one_two" from each string in the list and rebuild the list so that each entry only has "somethingX_somethingY"
. I know that in C, there is a strtok function that is useful for splitting into tokens, but I'm not sure if there is a method like that or a strategy to get that same effect in Python. Help me please?
Upvotes: 2
Views: 9811
Reputation: 375844
If you're literally trying to remove "_one_two" from the end of the strings, then you can do this:
tail_len = len("_one_two")
strs = [s[:-tail_len] for s in strs]
If you want to remove the last two underscore-separated components, then you can do this:
strs = ["_".join(s.split("_")[:-2]) for s in strs]
If neither of these is what you want, then let update the question with more details.
Upvotes: 3
Reputation: 838876
You can use split and a list comprehension:
l = ['_'.join(s.split('_')[:2]) for s in l]
Upvotes: 6
Reputation: 34438
I think this does what you're asking for.
s = "somethingX_somethingY_one_two"
splitted = s.split( "_" )
splitted = [ x for x in splitted if "something" in x ]
print "_".join( splitted )
Upvotes: 2