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.


import_contacts

You may also like:

Related Posts

  • Remove Urls from String in Python
    03 May

    Remove Urls from Text in Python

    Table of ContentsIntroductionWays to remove URLs from Text in PythonUsing the re.sub() function to remove URLs from Text in PythonUsing the re.findall() function to remove URLs from Text in PythonUsing the re.search() function to remove URLs from Text in PythonUsing the urllib.urlparse class to remove URLs from Text in PythonConclusion In this post, we will […]

  • 16 February

    Remove Backslash from String in Python

    Table of ContentsHow to remove backslash from string in python?Using replace() Function to Remove Backslash from String in PythonUsing the decode() Function to Remove Backslash from String in PythonUsing re Library Functions to Remove Backslash from String in PythonUsing strip() Function to Remove Backslash from String in PythonHow To Remove Backslash from Json String in […]

  • Remove quotation marks from String in Python
    13 February

    Remove Quotation Marks from String in Python

    Table of ContentsQuotes in PythonRemove Double Quotes from String in PythonUsing the replace() Function to Remove Double Quotes from String in PythonUsing the re.sub() Function to Remove Double Quotes from String in PythonUsing the for Loop to Remove Double Quotes from String in PythonUsing the join() Function to Remove Double Quotes from String in PythonUsing […]

  • Parentheses from String in Python
    08 February

    Remove Parentheses from String in Python

    Table of ContentsWays to Remove Parentheses from String in PythonUsing the replace() Function to Remove Parentheses from String in PythonUsing the re.Sub() Function to Remove Parentheses from String in PythonUsing the pandas.Str.Replace() Function to Remove Parentheses from String in PythonConclusion In this article, we will see how to remove parentheses from String in Python. Parentheses […]

  • Remove word from String in Python
    08 February

    Remove Word from String in Python

    Table of ContentsRemove Word from String in PythonHow to Remove Word from Sentence in PythonUsing the replace() functionUsing the re.sub() functionUsing the startswith() functionUsing the removeprefix() functionUsing the endswith() functionUsing the removesuffix() functionHow to Remove Duplicate Words from String in PythonUsing the set() functionUsing the set() and join() functionsUsing the join() and a user-defined functionUsing […]

  • Check if variable is String in Python
    13 January

    Check if variable is String in python

    Table of ContentsHow to check if a given variable is of the string type in Python?Using the isinstance() function.Using the type() function.Check if function parameter is String In this post, we will see what is a string in Python and how to check whether a given variable is a string or not. There are many […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.