Python delete in a string
I have these 3 strings:
开发者_Go百科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?
You can't. Create a new string with the pieces you want to keep.
','.join(s.split(',')[:4])
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.
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.
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'
>>>
精彩评论