Remove spaces from a string in Python
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 use replace() method.
s = "Python is fun"
s = s.replace(" ", "")
print(s)
Output
Pythonisfun
Explanation: s.replace(" ", "") replaces every space in s 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.
s = " Hello World "
s = s.strip()
print(s)
Output
Hello World
Explanation: s.strip() removes spaces from the start and end of s.
Removing Leading Spaces Only
If we only want to remove spaces from the beginning of the string, we can use lstrip().
s = " Hello World"
s = s.lstrip()
print(s)
Output
Hello World
Explanation: s.lstrip() removes spaces from the left side of s only.
Removing Trailing Spaces Only
Similarly, to remove spaces from the end of a string, we can use rstrip().
s = "Hello World "
s = s.rstrip()
print(s)
Output
Hello World
Explanation: s.rstrip() removes spaces from the right side of s only.
Related Articles:
- Python String replace() Method
- Python String strip() Method
- Python String lstrip() Method
- Python String rstrip() Method