In this tutorial, we will see how to remove spaces from String in Python.

Remove Spaces From String in Python:

We have different solutions to fulfil this requirement in python. Let’s see one by one.

1. Python rstrip():

Python rstrip() function is used to remove the spaces at the right side of a string.

str = ' hello  python string    '
str = str.rstrip()
print(str)

Output:

hello  python string

2. Python lstrip():

Python lstrip() function is used to remove the spaces at the left side of a string.

str = '      hello  python string '
str = str.lstrip()
print(str)

Output:

hello python string

3. Python strip():

Python strip() function is used to remove the spaces at both sides of a string.

str = '      hello python string    '
str = str.strip()
print(str)

Output:

hello python string

4. Remove Spaces From String using replace:

replace() function used to replace all the matching contents with the given content. Here I am going to replace all the white spaces with empty so that I can remove all white areas from the string.

str = '  hello python string    '
str= sentence.replace(" ", "")
print(str)

Output:

hellopythonstring

5. Remove Spaces From String using join:

join() function is used to join the array of strings.

str = ' hello  python string    '
str = " ".join(str.split())
print(str)

Output:

hello python string

6. Remove Spaces from String Python Regex:

import re

# Reg Expression
# Removing Begining of a String
str = '    hello  python   '
str = re.sub(r"^\s+", "", str, flags=re.UNICODE)
print("removed spaces at left side :",str)

# Ending of a string
str = '    hello  python   '
str = re.sub(r"\s+$", "", str, flags=re.UNICODE)
print("removed spaces at right side :",str)

# Removing Begining and Ending
str = '    hello  python   '
str = re.sub("^\s+|\s+$", "", str, flags=re.UNICODE)
print("removed spaces at both sides :",str)

# Removing all spaces
str = ' hello  python   '
pattern = re.compile(r'\s+')
str = re.sub(pattern, '', str)
print(str)

Output:

removed spaces at left side : hello  python   
removed spaces at right side :     hello  python
removed spaces at both sides : hello  python
removed all spaces: hellopython

Done!

References:

Happy Learning 🙂