How to remove spaces within a string in Python?

To remove spaces inside a Python string (str), you can use either the replace() method or regular expressions to delete the spaces. Here are examples of both methods:

Utilize the replace() method:

original_string = "Hello   World"
new_string = original_string.replace(" ", "")
print(new_string)

This will output: HelloWorld, with all spaces removed.

2. Utilize regular expressions.

import re

original_string = "Hello   World"
new_string = re.sub(r'\s+', '', original_string)
print(new_string)

This code uses regular expression \s+ to match one or more spaces and replace them with an empty string. The final output is: HelloWorld, a string without any spaces.

bannerAds