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?


import_contacts

You may also like:

Related Posts

  • 25 December

    Encode String to UTF-8 in Python

    Table of ContentsEncode String to UTF-8 in PythonUsing the encode() functionUsing the codecs.encode() functionConclusion The UTF-8 encoding is used by default in Python and represents 8-bit Unicode values. The upgrade to Python 3 saw a major change in using ASCII characters to Unicode characters by default for strings. Encode String to UTF-8 in Python This […]

  • 23 December

    How To Do Line Continuation in Python

    Table of ContentsUsing Backslash (\) OperatorLine Continuation in StringLine Continuation in Number ExpressionUsing Parentheses ()Line Continuation in StringLine Continuation in Number Expression Using Backslash (\) Operator We can use \ operator for line continuation in string and number expression as follows. Line Continuation in String To do line continuation in Python Strings: Use the backslash […]

  • 16 December

    Convert List to Comma Separated String in Python

    Table of ContentsUse .join() MethodUse .join() with map() MethodUse .join() with List Comprehension Use .join() Method To convert a list to a comma separated string in Python, use the .join() method. join() method takes all elements in an iterable and joins them into one string with delimiter as separator. [crayon-63da528c2dcf0045219031/] [crayon-63da528c2dcf5277611174/] First, we created a […]

  • 09 December

    Count Occurrences of Character in String in Python

    Table of ContentsUsing count() MethodUsing Naive for loopUsing List ComprehensionUsing re.findall() MethodUsing for loop with re.finditer() MethodUse the lambda Function with map()Use collections.Counter() Method Using count() Method Use String’s count() method to count occurrences of character in String in Python e.g. my_string.count(character). count() method returns number of occurrences of the character in String. [crayon-63da528c2de7b028266148/] We […]

  • 08 December

    Find Character in String in Python

    Table of ContentsUsing find() MethodUsing index() MethodUsing for Loop with re.finditer() MethodUsing list comprehension Using find() Method To find the character in a string in Python: Use the find() method to find the index of the first occurrence of the supplied character in the input String. Use an if statement to check if the returned […]

  • 05 December

    Remove Substring from String in Python

    Table of ContentsUse replace() MethodUse the split() Method with for loopUse split() with join() MethodUse re.sub() Method Use replace() Method To eliminate a substring from string in Python: Define and initiate my_string. Declare substring to remove it from my_string. Use replace() method to remove substring from string. e.g. my_string = my_string.replace(substring, "") [crayon-63da528c2f0ca635257288/] The code […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.