简体   繁体   中英

Python: Iterate over string with while loop

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?

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.

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