2

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?

Chris Headleand
  • 6,003
  • 16
  • 51
  • 69

3 Answers3

7

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?'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Using regex:

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

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

Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
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.

Community
  • 1
  • 1