Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

rstrip() function does not work in what I expected

I wanted to eliminate specific characters by using rstrip() function in python, but it didn’t work well to me.

Here is the code I wrote.

a = "happy! New! Year!!!"
print(a)
b = a.lower()
print(b)
c = b.rstrip('!')
print(c)

And this is the result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

happy! New! Year!!!
happy! new! year!!!
happy! new! year

The result I wanted was to output "happy new year", but the function just got rid of last three ‘!’. I have no idea why it happened.

>Solution :

The rstrip function only strips a given character appearing one or more times at the end of the entire string. To remove ! from the end of each word, we can use re.sub:

a = "happy! New! Year!!!"
output = re.sub(r'\b!+(?!\S)', '', a)
print(output)  # happy New Year
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading