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

use*_*287 56 python string split slice python-2.7

我试图在某个字符之前打印字符串的最后一部分.

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

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

x = 'http://test.com/lalala-134'
print x['-':0] # beginning at the end of the string, return everything before '-'
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 102

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

print x.rsplit('-', 1)[0]
Run Code Online (Sandbox Code Playgroud)

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

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

print x.rpartition('-')[0]
Run Code Online (Sandbox Code Playgroud)

只拆分一次,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'
Run Code Online (Sandbox Code Playgroud)

与...相同 str.rpartition()

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

  • 对,你的措辞有点含糊不清; 你在**某个字符之前要求*字符串**的最后一部分*; 你的意思是,我想.:-) (2认同)

dvi*_*ekh 5

split分区之间的区别是 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"
Run Code Online (Sandbox Code Playgroud)

并且partition将只用第一个分隔符来划分字符串,并且只返回列表中的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"
Run Code Online (Sandbox Code Playgroud)

因此,当您想要最后一个值时,您可以使用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"
Run Code Online (Sandbox Code Playgroud)