[英]Python : go backwards through a string, then remove everything after a specific character
I have a string, which after a character I wish to remove everything after the character. 我有一个字符串,在一个字符之后,我希望删除字符后的所有内容。 However, the issue is that I have multiple characters like this in the string and its only the characters after the last one which I wish to remove.
但是,问题是我在字符串中有多个这样的字符,而且只有我希望删除的最后一个字符。
for example: 例如:
str = "howdie how are you? are you good? sdfsdf"
str = str.RemoveEverythingAfterLast("?")
str = "howdie how are you? are you good?"
I was wondering if there was an efficient way to do this in python? 我想知道在python中是否有一种有效的方法可以做到这一点? I had thought of looping backwards through the string deleting characters 1 by 1 until I found the character I was looking for (in example the '?').
我曾经想过通过字符串向后循环删除字符1 1,直到找到我正在寻找的字符(例如'?')。 But I was wondering if there was a more efficient way to go about this?
但我想知道是否有更有效的方法来解决这个问题?
Use str.rpartition()
: 使用
str.rpartition()
:
''.join(string.rpartition('?')[:2])
Demo: 演示:
>>> string = "howdie how are you? are you good? sdfsdf"
>>> ''.join(string.rpartition('?')[:2])
'howdie how are you? are you good?'
Using regex: 使用正则表达式:
str = re.sub("(.*\?).*", "\\1", str)
capturing the group till the last ?
捕捉到最后一组
?
and replace it with captured group \\\\1
. 并用捕获的组
\\\\1
替换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.