Open In App

Remove spaces from a string in Python

Last Updated : 05 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

s = "Python is fun"

# Replace all spaces in string with an empty string
s = s.replace(" ", "")
print(s)

Output
Pythonisfun

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.

s = "   Hello World   "

# Remove any leading and trailing whitespace from string
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"

# Remove any leading whitespace from string
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   "

# Remove any trailing whitespace from string
s = s.rstrip()
print(s)

Output
Hello World

Explanation: s.rstrip() removes spaces from the right side of s only.



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg