hssss
hssss

Reputation: 141

Python delete in a string

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?

Upvotes: 3

Views: 613

Answers (4)

johnsyweb
johnsyweb

Reputation: 141820

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.

Upvotes: 3

gimel
gimel

Reputation: 86382

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

Upvotes: 0

Cristian Ciupitu
Cristian Ciupitu

Reputation: 20900

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.

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798774

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

','.join(s.split(',')[:4])

Upvotes: 6

Related Questions