Reputation: 25349
I'm trying to delete all the characters at the end of a string following the last occurrence of a '+'. So for instance, if my string is 'Mother+why+is+the+river+laughing' I want to reduce this to 'Mother+why+is+the+river'. I don't know what the string will be in advance though.
I thought of iterating backwards over the string. Something like:
while letter in my_string[::-1] != '+':
my_string = my_string[:-1]
This won't work because letter in not pre defined.
Any thoughts?
Upvotes: 0
Views: 9537
Reputation: 1121754
Just use str.rsplit()
:
my_string = my_string.rsplit('+', 1)[0]
.rsplit()
splits from the end of a string; with a limit of 1 it'll only split on the very last +
in the string and [0]
gives you everything before that last +
.
Demo:
>>> 'Mother+why+is+the+river+laughing'.rsplit('+', 1)[0]
'Mother+why+is+the+river'
If there is no +
in the string, the original string is returned:
>>> 'Mother'.rsplit('+', 1)[0]
'Mother'
As for your loop; you are testing against a reversed string and the condition returns True
until the last +
has been removed; you'd have to test in the loop for what character you just removed:
while True:
last = my_string[-1]
my_string = my_string[:-1]
if last == '+':
break
but this is rather inefficient compared to using str.rsplit()
; creating a new string for each character removed is costly.
Upvotes: 7