Hacky, but uses yield :
import string
li_test = [
("My string is #not very beautiful","My string is"),
("Are you 9 years old?","Are you "),
("this is the last example","this is the last "),
]
tolerated = string.ascii_letters
def rstrip_(s_in):
last = None
for char in s_in:
if char in tolerated:
last = char
yield char
elif char == ' ':
if last == ' ':
raise StopIteration()
last = char
yield char
else:
raise StopIteration()
for input_, exp in li_test:
got = "".join(rstrip_(input_))
msg = ":%s:<>:%s:" % (exp, got)
print (":%s:=>:%s:" % (input_, got))
#cheating a bit because I dunno if the last space is wanted.
assert exp.rstrip() == got.rstrip(), msg
output:
:My string is
:Are you 9 years old?:=>:Are you :
:this is the last example:=>:this is the last :
And yes, I had to wrap it all in a second function and join the characters there ...
source
share