3

I have these 3 strings:

YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs
YELLOW,SMALL,STRETCH,ADULT,Tdsfs
YELLOW,SMALL,STRETCH,ADULT,TD

I would like to remove everything after the last , including the comma. So i want to remove these parts ,T21fdsfdsfs, ,Tdsfs and TD. How could i do that in Python?

4 Answers 4

6

You can't. Create a new string with the pieces you want to keep.

','.join(s.split(',')[:4])
Sign up to request clarification or add additional context in comments.

3 Comments

You can also use -1 instead of 4 if you just want to remove the last part and do not know how many parts there will be.
-1 because Cristian really has the right idea IMO. I've done the equivalent in my own code many times.
@Karl Knechtel: I think that Ignacio assumed that only the first 4 fields are needed (and the rest are garbage), but only hssss can really clear things up.
5
s.rsplit(',', 1)[0]

Anyway, I suggest having a look at Ignacio Vazquez-Abrams's answer too, it might make more sense for your problem.

1 Comment

If there will be a variable amount of commas then this is the solution that doesn't break. A modification of Ignacio's answer has that feature as well but this one still creates less intermediate strings.
3

According to The Zen of Python:

There should be one-- and preferably only one --obvious way to do it.

...so here's a third, which uses rpartition:

>>> for item in catalogue:
...     print item.rpartition(',')[0]
... 
YELLOW,SMALL,STRETCH,ADULT
YELLOW,SMALL,STRETCH,ADULT
YELLOW,SMALL,STRETCH,ADULT

I haven't compared its performance against the previous two answers.

3 Comments

python -m timeit -n 20000000 '"YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs".rpartition(",")[0]' gives 0.301 usec per loop and python -m timeit -v -n 20000000 '"YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs".rsplit(",", 1)[0]' gives 0.489 usec per loop. I'm using python-2.7-8.fc14.1.x86_64 on Core 2 Duo E6400.
Neat! I see similar results, too. Thanks.
For completeness, python -m timeit -v -n 20000000 '",".join("YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs".split(",")[:4])' yields: 1.19 usec per loop.
0

If you refer to string elements, you can utilize str.rsplit() to separate each string, setting maxsplit to 1.

str.rsplit([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.

>>> lst = "YELLOW,SMALL,STRETCH,ADULT,T"
>>> lst.rsplit(',',1)[0]
'YELLOW,SMALL,STRETCH,ADULT'
>>> 

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.