how to get the last part of a string before a certain character?

后端 未结 2 393
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 08:15

I am trying to print the last part of a string before a certain character.

I\'m not quite sure whether to use the string .split() method or string slicing or maybe som

相关标签:
2条回答
  • 2021-01-30 08:57

    Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.

    x = 'http://test.com/lalala-134-431'
    
    a,b,c = x.split(-)
    print(a)
    "http://test.com/lalala"
    print(b)
    "134"
    print(c)
    "431"
    

    and partition will divide the string with only first delimiter and will only return 3 values in list

    x = 'http://test.com/lalala-134-431'
    a,b,c = x.partition('-')
    print(a)
    "http://test.com/lalala"
    print(b)
    "-"
    print(c)
    "134-431"
    

    so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string

    x = 'http://test.com/lalala-134-431'
    a,b,c = x.partition('-')
    print(a)
    "http://test.com/lalala-134"
    print(b)
    "-"
    print(c)
    "431"
    
    0 讨论(0)
  • 2021-01-30 09:03

    You are looking for str.rsplit(), with a limit:

    print x.rsplit('-', 1)[0]
    

    .rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

    Another option is to use str.rpartition(), which will only ever split just once:

    print x.rpartition('-')[0]
    

    For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

    Demo:

    >>> x = 'http://test.com/lalala-134'
    >>> print x.rsplit('-', 1)[0]
    http://test.com/lalala
    >>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
    'something-with-a-lot-of'
    

    and the same with str.rpartition()

    >>> print x.rpartition('-')[0]
    http://test.com/lalala
    >>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
    'something-with-a-lot-of'
    
    0 讨论(0)
提交回复
热议问题