0

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?

1
  • to quickly answer your question, you don't need letter : while my_string[-1] != '+': is sufficient. rfind and rsplit based answers are better, though. Commented Sep 5, 2013 at 9:03

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.