Remove Spaces From Strings in Python

By Hemanta Sundaray on 2021-08-29

We can remove spaces from both ends of a string using the strip() method.

topic = "   Machine Learning   "

print(topic.strip())
# "Machine Learning"

To remove space just from the right or left, we can use rstrip() & lstrip() respectively:

topic = "   Machine Learning   "

print(topic.rstrip())
# "   Machine Learning"

print(topic.lstrip())
# "Machine Learning   "

Join the Newsletter