如何在某个字符之前获取字符串的最后一部分? [英] how to get the last part of a string before a certain character?

查看:37
本文介绍了如何在某个字符之前获取字符串的最后一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

x = 'http://test.com/lalala-134'print x['-':0] # 从字符串末尾开始,返回'-'之前的所有内容

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

解决方案

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

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

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

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

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

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

演示:

<预><代码>>>>x = 'http://test.com/lalala-134'>>>打印 x.rsplit('-', 1)[0]http://test.com/lalala>>>'有很多破折号的东西'.rsplit('-', 1)[0]'有很多东西'

str.rpartition()

相同<预><代码>>>>打印 x.rpartition('-')[0]http://test.com/lalala>>>'有很多破折号的东西'.rpartition('-')[0]'有很多东西'

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 something else.

Here is some code that doesn't work but I think shows the logic:

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

Note that the number at the end will vary in size so I can't set an exact count from the end of the string.

解决方案

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'

这篇关于如何在某个字符之前获取字符串的最后一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆