Replace space with underscore in Python

Strings are an essential data type in programming. In Python, we can treat strings as an iterable of characters, and can perform a variety of functions and operations on them. Replacing characters in a string is one such operation.

Ways to replace space with underscore in Python

In this article, we will discuss various methods to replace space with underscore in Python.

Using the for loop

The for loop can iterate over a string in Python. In every iteration, we will compare the character with whitespace. If the match returns true, we will replace it with an underscore character.

For example,

Output:

hello_welcome_to_java_2_blog

In the above example,

  • We iterate over the string s using the for loop.
  • If the character is a space, we concatenate _ to string a.
  • If not, then the encountered character is appended.

Using the replace() function

We can use the replace() function to replace a substring from a string. We can also specify how many occurrences we want to replace within the function.

To replace all instances of space in a string with an underscore, we will specify only these two characters within the function.

For example,

Output:

hello_welcome_to_java_2_blog

Using the re.sub() function

We can use regular expressions to create patterns that can match with parts of strings to perform various operations.

The re.sub() function replaces the substring that matches with a given pattern. We can use it to replace whitespaces with an underscore in a string.

See the code below.

Output:

hello_welcome_to_java_2_blog

In the above example,

  • We import the re module that lets us work with regular expressions in Python.
  • The \s+ pattern identifies any space in the string.
  • The sub() function replaces these spaces with underscores.

Using the split() and join() function

The join() function can combine the elements of an iterable with a given separator character. To replace whitespaces with an underscore with this function, first, we will have to use the split() method.

The split() function will split the string to a list based on some separator. By default, this separator character is a space.

We will split the string to a list based on whitespace, and then join these elements using the join() function and have the underscore character as the separator.

We implement this in the code below.

Output:

hello_welcome_to_java_2_blog

Conclusion

In this tutorial, we discussed how to replace a space with an underscore in a string. The replace() and re.sub() function prove to be the most straightforward methods. The for loop method is a lengthy and inefficient method. The join() and split() functions can be a little fast, but this method will not work for a group of whitespace characters.

That’s all about how to replace space with underscore in Python.

Was this post helpful?

Leave a Reply

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