如何在某个字符之前获取字符串的最后一部分?

时间:2013-04-06 13:32:20

标签: python string python-2.7 split slice

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

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

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

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

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

2 个答案:

答案 0 :(得分:95)

您正在寻找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'

答案 1 :(得分:1)

拆分 分区 之间的差异将被拆分返回列表,不带分隔符并将分裂到字符串中的分隔符,即

x = 'http://test.com/lalala-134-431'

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

分区 会将字符串除以第一个分隔符,并且只返回列表中的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.partition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"