Replace Underscores with Spaces in Python

# 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

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
Project

### Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
Details
Project

### Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

Details