How To Replace All Spaces In A String In Python

In this tutorial, we will learn how to replace all spaces in a string in Python. This is useful in situations where you need to format a string without spaces or when you want to replace spaces with a specific character.

Step 1: Initial String

First, let’s create a string with spaces that we want to replace:

Step 2: Replacing Spaces Using string.replace()

The built-in string.replace() method in Python can be used to replace all occurrences of a substring with another substring. In this case, we will replace all spaces with a specific character or no character at all.

To replace all spaces with a specific character, you can use the following code:

The variable replace_char holds the character which will replace the spaces in the string. Here we have used an underscore (_) as the replacement character.

Step 3: Replacing Spaces with No Character (Removing Spaces)

If you want to remove all spaces from the string, simply use an empty string as the replacement character:

Step 4: Print the Result

To see the result, print the new string:

This_is_an_example_string_with_spaces.

Alternative Method: Using str.join()

An alternative way to replace spaces in a string is to use the str.join() method. This method can be useful if you want to replace spaces with a specific text or delimiter.

To replace spaces with a specific character, you can use the following code:

Full Code

Output

This_is_an_example_string_with_spaces.
Thisisanexamplestringwithspaces.
This_is_an_example_string_with_spaces.

Conclusion

In this tutorial, we have learned how to replace all spaces in a string in Python using the string.replace() method and an alternative approach with the str.join() method. With these techniques, you can easily format a string without spaces or replace spaces with any character or text as per your requirements.