Replace whitespaces with underscore in Python

In this Python tutorial, we will learn about the techniques through which we can replace all whitespaces with underscores in a string using the Python Programming language.

Table Of Contents

There are different ways to replace all whitespaces with underscores in a string. Let’s discuss them one by one.

Method 1 : Using for loop

We can not modify the strings in Python because strings are immutable. So, we will create a new string and copy all characters from original string to the new string one by one using a for loop. But before copying, we will check if it is a whitespace or not. If yes, then instead of adding a whitespace, we will add an underscore in the new string. In the end, we will assign the new string to the main string variable. It will give an effect that we have replaced all the whitespaces in the string with the underscores. Let’s see the example code below.

CODE :

example_string = 'using for loop to iterate over the string'

new_string = ''

# Iterate over all characters of string by index position
for i in range( len( example_string ) ):
    # checking for empty spaces
    if example_string[i] == ' ':
        # replacing empty spaces with underscore
        new_string = new_string + '_'
    else:
        # copying other chars of the string.
        new_string = new_string + example_string[i]

example_string = new_string

# final output of replaced string with underscore.
print(example_string)

OUTPUT :

<class 'str'>
using_for_loop_to_iterate_over_the_string

In the above example, we have replaced all whitespaces with the underscores in the string.

Method 2 : Using str.replace()

Another method that we can use to replace whitespaces with underscore in a string, is the replace() method of class str. It takes two arguments,

  • old value : The value which needs to be replaced.
  • new value : The value with which the old value will be replaced.

It replaces all the occurrences of a given substring with the given replacement string in the copy of calling string object. It returns a copy of string with the replaced contents.

We can use this function to replace all the instances of whitespaces (old value) with the underscores (new value). Let’s see an example,

example_string = 'using str.replace() to replace whitespace with "_"'

# using str.replace() to replace all whitespaces with the underscores.
example_string = example_string.replace(' ', '_')

print(example_string)

OUTPUT :

<class 'str'>
using_str.replace()_to_replace_whitespace_with_"_"

In the above example, we have replaced all whitespaces with the underscores in the string.

Method 3 : Using re.sub()

In Python, the regex module provides a function for the string substitution i.e. sub(). This method takes three arguments i.e. a regex pattern, a replacement string and a string in which replacement needs to be done. Then it looks for all substrings in the given string that matches the given pattern and replaces them with the given replacement string. We can use this to replace whitespaces with underscore in a string. Let’s see an example,

CODE :

import re

example_string = 'using sub() function to replace whitespace with underscore'

# Replace whitespaces with underscores in string using sub()
example_string = re.sub(' ', '_', example_string)

print(example_string)

OUTPUT :

using_sub()_function_to_replace_whitespace_with_underscore

In the above example, we have successfully replaced the whitespaces with underscores. Here, we passed following paratmeters in the sub() function,
* A whitespace as first parameter. It will act like a regex pattern.
* An underscore as the second argument. Thi sis the replacement string.
* A string in which we need to replace the whitespaces with underscores.

The sub() function replaced all the whitespaces with the second argument i.e. an underscore in the copy of the given string.

This method is also usefull if we want to replace one or more whitespaces with an underscore. For example,

import re

example_string = 'The    sample       string'

# Replace whitespaces with underscores in string using sub()
example_string = re.sub('\s+', '_', example_string)

print(example_string)

Output

The_sample_string

Here, the regex pattern “\s+” selected one or more whitespaces and using the sub() function we replaced them with a single underscore.

Summary

In this Python tutorial, we learned about three different methods by using which we can replace whitespaces with underscore in a string. You can always use all the methods above, but the method with easiest syntax is the str.replace() method, just provide the parameters and done, no need to iterate or import any module.

Also we have used Python 3.9.12 for writing example codes. Type python –version in your terminal to check your python version. Always try to read, write and run example codes on your machine to understand properly. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top