Replace underscores with spaces in Python

avatar

Borislav Hadzhiev

Last updated: Jun 21, 2022

banner

Photo from Unsplash

Replace underscores with spaces in Python #

Use the str.replace() method to replace underscores with spaces, e.g. result = my_str.replace('_', ' '). The str.replace() method will replace all occurrences of an underscore with a space in the string.

main.py
my_str = 'one_two_three' result = my_str.replace('_', ' ') print(result) # 👉️ 'one two three'

We used the str.replace() method to replace underscores with spaces 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.

Alternatively, you can use the str.join() and str.split() methods.

To replace underscores with spaces in Python:

  1. Use the str.split() method to split the string on each underscore.
  2. Call the join() method on a string containing a space.
  3. The join method will join the words with a space separator.
main.py
my_str = 'one_two_three' result = ' '.join(my_str.split('_')) print(result) # 👉️ 'one two three'

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

main.py
my_str = 'one_two_three' print(my_str.split('_')) # 👉️ ['one', 'two', 'three']

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

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

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

main.py
my_str = 'one_two_three' result = ' '.join(my_str.split('_')) print(result) # 👉️ 'one two three'

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 the elements.

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.