How to replace Spaces with Underscores in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
3 min

banner

# Table of Contents

  1. Replace spaces with underscores in Python
  2. Replace spaces with underscores using re.sub()
  3. Replace spaces with underscores using split() and join()
  4. Replace spaces with underscores using a for loop

# Replace spaces with underscores in Python

To replace spaces with underscores in Python:

  1. Call the replace() method on the string.
  2. Pass a string containing a space and a string containing an underscore to the method.
  3. The replace() method will return a string with all spaces replaced by underscores.
main.py
my_str = 'bobby hadz com' result = my_str.replace(' ', '_') print(result) # ๐Ÿ‘‰๏ธ 'bobby_hadz_com'

replace spaces with underscores

The code for this article is available on GitHub

We used the str.replace() method to replace spaces with underscores in a string.

The str.replace() method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.

The method takes the following parameters:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly the first count occurrences are replaced (optional)
Note that the method doesn't change the original string. Strings are immutable in Python.

If you need to replace all whitespace characters in a string with underscores, use the re.sub() method.

# Replace spaces with underscores using re.sub()

This is a three-step process:

  1. Import the re module from the standard library.
  2. Use the re.sub() method to replace all whitespace characters with underscores.
  3. The returned string will have all whitespace chars replaced with underscores.
main.py
import re my_str = 'bobby hadz com' result = re.sub(r"\s+", '-', my_str) print(result) # ๐Ÿ‘‰๏ธ 'bobby-hadz-com'

replace spaces with underscores using rewsub

The code for this article is available on GitHub

The re.sub() method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.

The \s character matches Unicode whitespace characters like [ \t\n\r\f\v].

The plus + is used to match the preceding character (whitespace) 1 or more times.

This helps us replace multiple whitespace characters with a single underscore. Alternatively, you can use the str.join() and str.split() methods.

# Replace spaces with underscores using split() and join()

This is a three-step process:

  1. Use the str.split() method to split the string on each whitespace character.
  2. Call the join() method on a string containing an underscore.
  3. The join method will join the words with an underscore separator.
main.py
my_str = 'bobby hadz com' result = '_'.join(my_str.split()) print(my_str.split()) print(result) # ๐Ÿ‘‰๏ธ 'bobby_hadz_com'

replace spaces with underscores using split and join

The code for this article is available on GitHub

We used the str.split() method to split the string on each whitespace character.

main.py
my_str = 'bobby hadz com' # ๐Ÿ‘‡๏ธ ['bobby', 'hadz', 'com'] print(my_str.split())

The str.split() method splits the string into a list of substrings using a delimiter.

If a separator is not provided, the method regards consecutive whitespace characters as a single separator.

main.py
my_str = 'bobby hadz com' # ๐Ÿ‘‡๏ธ ['bobby', 'hadz', 'com'] print(my_str.split())

The last step is to use the str.join method to join the list of words with an underscore separator.

main.py
my_str = 'bobby hadz com' result = '_'.join(my_str.split()) print(result) # ๐Ÿ‘‰๏ธ 'bobby_hadz_com'

The str.join() method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between elements.

# Replace spaces with underscores using a for loop

You can also use a for loop to replace the spaces in a string with underscores.

main.py
my_str = 'bobby hadz com' new_str = '' for char in my_str: if char == ' ': new_str += '_' else: new_str += char print(new_str) # ๐Ÿ‘‰๏ธ bobby_hadz_com

replace spaces with underscores using for loop

The code for this article is available on GitHub

We declared a new variable that stores an empty string and use a for loop to iterate over the original string.

On each iteration, we check if the current character is a space.

If the condition is met, we add an underscore to the new variable.

Otherwise, we add the current character to the variable.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev