繁体   English   中英

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

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

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

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

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

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

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

您正在寻找具有限制的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'

拆分分区之间的区别是拆分返回没有分隔符的列表,并将分割到字符串中的分隔符即可

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将仅使用第一个分隔符划分字符串,并且只返回列表中的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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM