Python delete in a string

后端 未结 4 1613
长情又很酷
长情又很酷 2021-01-21 08:51

I have these 3 strings:

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

相关标签:
4条回答
  • 2021-01-21 08:57

    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.

    0 讨论(0)
  • 2021-01-21 08:59

    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'
    >>> 
    
    0 讨论(0)
  • 2021-01-21 09:06
    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.

    0 讨论(0)
  • 2021-01-21 09:08

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

    ','.join(s.split(',')[:4])
    
    0 讨论(0)
提交回复
热议问题