Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so:
Using replace() method
To remove all spaces from a string, we can usereplace()method.
Pythons="Python is fun"s=s.replace(" ","")print(s)
Explanation: s.replace(" ", "") replaces every space ins with an empty string "", effectively removing them.
Removing Leading and Trailing Spaces
Sometimes, we only need to remove spaces from the start and end of a string while leaving the inner spaces untouched. In such cases,strip() method is ideal.
Pythons=" Hello World "s=s.strip()print(s)
Explanation:s.strip() removes spaces from the start and end ofs.
Removing Leading Spaces Only
If we only want to remove spaces from the beginning of the string, we can uselstrip().
Pythons=" Hello World"s=s.lstrip()print(s)
Explanation:s.lstrip() removes spaces from the left side ofs only.
Removing Trailing Spaces Only
Similarly, to remove spaces from the end of a string, we can userstrip().
Pythons="Hello World "s=s.rstrip()print(s)
Explanation:s.rstrip() removes spaces from the right side ofs only.
Related Articles:
Python program to remove spaces from a string