Replace Underscores with Spaces in Python

In many programming languages, underscores are used to separate words, which is called snake case (i.e. snake_case). This is especially true in Python, which can use underscores to separate module names, function names, and variable names. You've probably encountered this format in other areas as well, like in filenames.

Regardless of where you see this, you may need to convert these underscores to spaces in your code. We'll see how to do that here.

Replace Method

The simplest way to achieve this is to use the string's replace(substr, new_str) method, which takes a substring as an argument, as well as the new string to replace it with.

For our use-case, we want to replace underscores with spaces, which looks like this:

>>> underscore_str = "hello_world"
>>> underscore_str.replace("_", " ")
'hello world'

Note that the replace method returns a new string, rather than modifying the original. So it does not make the change in place. In order to change the string stored in our variable, underscore_str, we need to re-assign it:

>>> underscore_str = "hello_world"
>>> underscore_str = underscore_str.replace("_", " ")
>>> underscore_str
'hello world'

Split and Join

Another way to replace all underscores with spaces is to use the string's split(substr) and join(str) methods.

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

The split method works by splitting the string into a list of substrings, where each substring was separated by the given substring. The join method is called on a list of strings and joins them together into a single string, separating them with the given separator string.

Here you can see how the split method creates a list out of the given string:

>>> underscore_str = "hello_world"
>>> underscore_str.split("_")
['hello', 'world']

And here is how the join method joins the list of strings back into a single string:

>>> ['hello', 'world'].join(" ")
'hello world'

And finally, putting it all together:

>>> underscore_str = "hello_world"
>>> underscore_str.split("_").join(" ")
'hello world'
Last Updated: July 1st, 2022
Was this helpful?

Ā© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms