【问题标题】:how to get the last part of a string before a certain character?如何在某个字符之前获取字符串的最后一部分?
【发布时间】:2013-03-28 21:50:05
【问题描述】:

我正在尝试在某个字符之前打印字符串的最后一部分。

我不太确定是使用字符串 .split() 方法还是字符串切片或其他方法。

这是一些不起作用的代码,但我认为显示了逻辑:

x = 'http://test.com/lalala-134'
print x['-':0] # beginning at the end of the string, return everything before '-'

请注意,末尾的数字大小会有所不同,因此我无法从字符串末尾设置确切的计数。

【问题讨论】:

    标签: python string python-2.7 split slice


    【解决方案1】:

    您正在寻找str.rsplit(),有一个限制:

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

    .rsplit() 从输入字符串的末尾搜索拆分字符串,第二个参数将拆分的次数限制为一次。

    另一种选择是使用str.rpartition(),它只会分裂一次:

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

    如果只拆分一次,str.rpartition() 也是更快的方法;如果需要多次拆分,只能使用str.rsplit()

    演示:

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

    str.rpartition()一样

    >>> print x.rpartition('-')[0]
    http://test.com/lalala
    >>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
    'something-with-a-lot-of'
    

    【讨论】:

    • 非常感谢,我使用了print x.rsplit('-',1)[1],它成功了,谢谢。我也刚刚遇到print x.rpartition('-')[2],这似乎也有效!再次感谢!
    • 对,你的措辞有点模棱两可;您要求*字符串的最后一部分某个字符之前*;你是说之后,我猜。 :-)
    • 但是我很棒的cmets! '从字符串的末尾开始',我明白你的意思哈哈。
    【解决方案2】:

    splitpartition 的区别是 split 返回列表没有分隔符并将在字符串中分割到分隔符的地方,即

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

    partition 将仅使用 first 分隔符分割字符串,并且只会在列表中返回 3 个值

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

    所以你想要最后一个值,你可以使用 rpartition 它以相同的方式工作,但它会从字符串末尾找到分隔符

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

    【讨论】:

    • 最后一个例子应该是 x.rpartition 而不是 x.partition,是吗?
    猜你喜欢
    • 2020-09-17
    • 2020-05-21
    • 1970-01-01
    • 2020-09-13
    • 2013-05-04
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多