Replace space with underscore in Python
Strings are a fundamental information type in programming. In Python, we can regard strings as iterable characters and can play out various capabilities and procedures on them. Supplanting characters in a string is one such activity.
Ways to replace space with an underscore in Python
In this article, we will examine different techniques to supplant or replace space with an underscore in Python.
Method 1: Using the for loop
The for loop can emphasize over a string in Python. In each emphasis, we will contrast the character and whitespace. Assuming the match returns valid, we will supplant it with an underscore.
a = "Coding with Amandeep" a1 = "" for i in range(len(a)): if a[i] == ' ': a1 = a1 + '_' else: a1 = a1 + a[i] print(a1)
Method 2: Using the replace() function
A substring from a string can be replaced using the
replace() method. The number of instances we wish to replace within the function may also be specified. We will only supply these two characters within the method in order to replace any instances of space in a string with an underscore.
a = "Coding with Amandeep" a = a.replace(' ', '_') print(a)
Method 3: Using the re.sub() function
To generate patterns that can match certain sections of strings and carry out various actions, regular expressions are used. The substring that fits the specified pattern is replaced using the
re.sub() method. It may be used to replace any whitespace in a string with an underscore.
import re s = "Coding with Ammy" a = re.sub('\s+', '_', s) print(a)
Method 4: Using the split() and join() function
Using a separator, the
split() method will divide the text into a list. The space character is used as a separator by default.
The string will be divided into a list based on white space, and these components will be joined using the
join() method with the underscore character serving as the separator.
s = "Coding with Ammy" s = "_".join(s.split()) print(s)
In this instructional exercise, we examined how to supplant a space with a highlight in a string. The
re.sub() capabilities end up being the clearest strategies. The for-loop technique is an extensive and wasteful strategy. The
split() capabilities can be somewhat quick, however, this technique won’t work for a gathering of whitespace characters.
Leave a Reply