You are currently viewing How to Remove Spaces from a String in Python

How to Remove Spaces from a String in Python

One of the most common tasks that a Python programmer will have to do is remove spaces from a string. This can be accomplished in a number of ways. Let’s have a look at it.

One of the most common tasks that a Python programmer will have to do is remove spaces from a string. This can be accomplished in a number of ways. Let’s have a look at it.

Method 1: Remove Spaces from a String using str.replace()

The most straightforward method is to use the str.replace() method. The way we’ll do this is by creating an empty string in which all the spaces will be replaced with nothing. Here’s how to code it.

Code:

str = "  This is a String.  "
str_final = str.replace(" ", "")
print("Orignal string:",str)
print("String after space removal:", str_final)

Output:

Orignal string:   This is a String.  
String after space removal: ThisisaString.

Method 2: Remove Spaces from a String using str.strip()

So, alternatively, instead of replacing the space and turning it into nothing, we could have used str.strip(), which removes white-space characters from both ends of a string. Let’s try it out.

Code:

str = "  This is a String.  "
str_final = str.strip()
print("Orignal string:", str)
print("String after space removal:", str_final)

Output:

Orignal string:   This is a String.  
String after space removal: This is a String.

You can also use lstrip() and rstrip() methods to remove spaces from text.

Method 2.1: Remove Spaces using lstrip()

If you need to only strip the left side of a string, you can use the lstrip() method.

Code:

str = "  This is a String.  "
str_final = str.lstrip()
print("Orignal string:", str)
print("String after left space removal:", str_final)

Output:

Orignal string:   This is a String.  
String after left space removal: This is a String.  
Method 2.2: Remove Spaces using rstrip()

The rstrip() method can also be used to remove spaces only from the right side of the text.

Code:

str = "  This is a String.  "
str_final = str.rstrip()
print("Orignal string:", str)
print("String after right space removal:", str_final)

Output:

Orignal string:   This is a String.  
String after right space removal:   This is a String.

References:

https://docs.python.org/3/

Leave a Reply