在 Python 中选择字符串的最后一个字符直到空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19303429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select last chars of string until whitespace in Python
提问by Paolo
Is there any efficient way to select the last characters of a string until there's a whitespace in Python?
有没有什么有效的方法来选择字符串的最后一个字符,直到 Python 中有空格?
For example I have the following string:
例如,我有以下字符串:
str = 'Hello my name is John'
I want to return 'John'. But if the str was:
我想返回“约翰”。但如果 str 是:
str = 'Hello my name is Sally'
I want to retrun 'Sally'
我想重播“莎莉”
采纳答案by Rohit Jain
Just split the string on whitespace, and get the last element of the array. Or use rsplit()
to start splitting from end:
只需在空格上拆分字符串,并获取数组的最后一个元素。或用于rsplit()
从末尾开始拆分:
>>> st = 'Hello my name is John'
>>> st.rsplit(' ', 1)
['Hello my name is', 'John']
>>>
>>> st.rsplit(' ', 1)[1]
'John'
The 2nd argument specifies the number of split
to do. Since you just want last element, we just need to split once.
第二个参数指定split
要做的事情的数量。由于您只需要最后一个元素,我们只需要拆分一次。
As specified in comments, you can just pass None
as 1st argument, in which case the default delimiter which is whitespace will be used:
正如注释中所指定的,您可以只传递None
第一个参数,在这种情况下,将使用默认的空格分隔符:
>>> st.rsplit(None, 1)[-1]
'John'
Using -1
as index is safe, in case there is no whitespace in your string.
使用-1
as index 是安全的,以防字符串中没有空格。
回答by MJ Howard
It really depends what you mean by efficient, but the simplest (efficient use of programmer time) way I can think of is:
这真的取决于你所说的高效是什么意思,但我能想到的最简单(有效利用程序员时间)的方法是:
str.split()[-1]
This fails for empty strings, so you'll want to check that.
这对于空字符串失败,因此您需要检查一下。
回答by mgoldwasser
I think this is what you want:
我认为这就是你想要的:
str[str.rfind(' ')+1:]
str[str.rfind(' ')+1:]
this creates a substring from str
starting at the character after the right-most-found-space, and up until the last character.
这将创建一个子字符串,str
从最右侧找到的空格之后的字符开始,直到最后一个字符。
This works for all strings - empty or otherwise (unless it's not a string object, e.g. a None object would throw an error)
这适用于所有字符串 - 空或其他(除非它不是字符串对象,例如 None 对象会抛出错误)