Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : go backwards through a string, then remove everything after a specific character

Tags:

python

string

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?

like image 236
Chris Headleand Avatar asked Aug 23 '26 17:08

Chris Headleand


2 Answers

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?'
like image 157
Martijn Pieters Avatar answered Aug 25 '26 08:08

Martijn Pieters


Using regex:

str = re.sub("(.*\?).*", "\\1", str)

capturing the group till the last ? and replace it with captured group \\1.

like image 23
Sabuj Hassan Avatar answered Aug 25 '26 06:08

Sabuj Hassan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!