开发者

python ............. delete [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Python delete in a string

I have the following list which has 3 elements:

YELLOW,SMALL,STRETCH,ADULT,T

YELLOW,SMALL,STRETCH,ADULT,T

YELLOW,SMALL,STRETCH,CHILD,F

I would like to remove ev开发者_StackOverflow中文版erything after the last comma.. Note that I could have more than one character after the last comma. How can I do that?

Thanks


If you name your string s it would be:

s = s[:s.rfind(",")+ 1] 

remove the one if don't want the comma at the end.


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


Try this:

In [84]: s = 'YELLOW,SMALL,STRETCH,ADULT,Tkj'

In [85]: re.search('(.*,)(.*)$', s).groups()
Out[85]: ('YELLOW,SMALL,STRETCH,ADULT,', 'Tkj')
In [86]: (a, b) = re.search('(.*,)(.*)$', s).groups()

a will contain the part you want and b will contain the part you want to delete

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜