Remove spaces from a string in Python
Last Updated :
05 Nov, 2024
In Python, removing spaces from a string is a common task that can be handled in multiple ways. In this article we will explore different methods to achieve this. The simplest way to remove all spaces from a string is using replace() method.
Using replace() method
To remove all spaces from a string, we can use replace() method.
Python
s = "Python is fun"
# Replace all spaces in string with an empty string
s = s.replace(" ", "")
print(s)
Explanation: s.replace(” “, “”) replaces every space in s with an empty string “”, effectively removing them.
Let’s explore different methods to remove spaces from a string:
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.
Python
s = " Hello World "
# Remove any leading and trailing whitespace from string
s = s.strip()
print(s)
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().
Python
s = " Hello World"
# Remove any leading whitespace from string
s = s.lstrip()
print(s)
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().
Python
s = "Hello World "
# Remove any trailing whitespace from string
s = s.rstrip()
print(s)
Explanation: s.rstrip() removes spaces from the right side of s only.