Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Division in Python

Tags:

python

string

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?

like image 679
Brian Avatar asked Dec 13 '25 05:12

Brian


2 Answers

You can use split and a list comprehension:

l = ['_'.join(s.split('_')[:2]) for s in l]
like image 102
Mark Byers Avatar answered Dec 14 '25 17:12

Mark Byers


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.

like image 44
Ned Batchelder Avatar answered Dec 14 '25 19:12

Ned Batchelder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!