简体   繁体   中英

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? 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 '?'). But I was wondering if there was a more efficient way to go about this?

Use 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 .

You can use str.rfind and slicing :

>>> string = "howdie how are you? are you good? sdfsdf"
>>> string[:string.rfind("?") + 1]
'howdie how are you? are you good?'
>>>

The + 1 will cause the ? to be left on the end of the returned string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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