Replace Spaces With Underscores in Python
In this guide, we will explore various methods for replacing spaces with underscores, but you can apply these techniques to substitute any character with another of your choosing.
Replace spaces with underscores using the replace() method
To replace spaces with underscores using the replace()
method in Python:
- Call the
replace()
method on the string you want to modify. - Pass two arguments to the
replace()
method: the first is the substring we want to replace (a space character" "
) and the second is the string we want to replace it with (an underscore"_"
). - The
replace()
method returns a new string with all the occurrences of spaces replaced with underscores.
Here, is an example:
my_str = "python is awesome"
new_str = my_str.replace(" ", "_")
print(new_str) # Output: python_is_awesome
The replace()
method is used to perform a simple replacement of a substring with another string.
However, if we need to search for a complex pattern and replace it with a string, we should use the re.sub()
method from the re
module. This method allows us to use regular expressions to match patterns in the string and replace them with another string.
Replace whitespaces with underscores using the re.sub() method
When working with strings in Python, it may sometimes be necessary to replace all whitespace characters (such as spaces, tabs, carriage returns, line feeds, or form feeds) with another character. This can be achieved using the re.sub()
method from the re
module.
In this guide, we will replace all whitespaces with underscores using the re.sub()
method.
To replace spaces with underscores using the re.sub()
method:
- First, we have to import the regular expression
re
module. - Use
re.sub()
to replace all whitespaces with underscores in a string. The first argument is the pattern to search for ("\s"
), the second is the string we want to replace it with ("_"
), and the third is the string to perform the replacement on. - The
re.sub()
method returns a new string with all the occurrences of spaces replaced with underscores.
Here, is an example:
import re
my_str = "python\tis awesome"
new_str = re.sub("\s", "_", my_str)
print(new_str) # Output: python_is_awesome
The \s
matches all whitespace characters like space, tab, carriage return, line feed, or form feed.
We can also pass a string with the space character " "
in the re.sub()
method if we only want to replace the space character.
String with multiple spaces between words
If a string contains multiple spaces between words and you want to replace them with a single underscore or another character, you can use the re.sub()
method from the re
module.
To do this, we have to pass a regular expression that matches one or more space characters (" +"
) as the search value and an underscore ("_"
) as the replacement value.
Here, is an example:
import re
my_str = "python is awesome"
new_str = re.sub(" +", "_", my_str)
print(new_str) # Output: python_is_awesome
new_string_two = re.sub(" ", "_", my_str)
print(new_string_two) # Output: python___is_awesome
The +
character in a regular expression matches the previous character one or more times.
E.g.
"e+"
matches "ee"
and "e"
in the string "breeze"
.
Whereas, "e"
matches 'e'
, 'e'
, and 'e'
in the string "breeze"
.
In our example, the regex pattern " +"
matches one or more spaces. The re.sub()
method searches for all the occurrences of one or more spaces in the string my_str
and replaces them with an underscore.
Note: Notice that there is a space character before the +
character.
String with leading and trailing spaces
To replace spaces with underscores in a string that has leading and trailing spaces, we first need to use the trim()
method to remove them. Then, we can use either the replace()
or re.sub()
method to replace spaces with underscores.
For example:
my_str = " python is awesome "
stripped_str = my_str.strip()
new_str = stripped_str.replace(" ", "_")
print(new_str) # Output: python_is_awesome
Replace spaces with underscores using the split() and join() method
To replace spaces with underscores using the split()
and join()
method:
- First, we split the string into a list of substrings at each occurrence of space using the
split()
method. - Second, we join the list of substrings using the
join()
method with an underscore as a separator.
Here is an example:
my_str = "python is awesome"
list_str = my_str.split()
new_str = "_".join(list_str)
print(new_str) # python is awesome
Note: The split()
method also takes a separator. The default separator is any whitespace.
Replace spaces with underscores using list comprehension
Many Python developers find list comprehension to be a powerful and concise tool. If you’re familiar with this technique, you can use it to replace spaces with underscores in a string.
Here, is an example:
my_str = "python is awesome"
list_str = ["_" if x == " " else x for x in my_str]
print(list_str)
# Output: ['p', 'y', 't', 'h', 'o', 'n', '_', 'i', 's', '_', 'a', 'w', 'e', 's', 'o', 'm', 'e']
new_str = "".join(list_str)
print(new_str) # Output: python_is_awesome
First, we use list comprehension to create a list list_str
. The logic is simple: if a character is a space, we replace it with an underscore; otherwise, we keep the character unchanged.
Second, we use the join()
method to combine all the elements of the list list_str
into a single string. We pass an empty string as the delimiter to join the elements without any separation.
Replace spaces with underscores using the for loop
We can also use the good old for
loop to replace spaces with underscores.
For example:
my_str = "python is awesome"
new_str = ""
for char in my_str:
if char == " ":
new_str += "_"
else:
new_str += char
print(new_str) # Ouput: python_is_awesome
In the above example:
- We used
for
loop to iterate over each character of a stringmy_str
. - If the character is a space, we append an underscore to a new string
new_str
. Otherwise, we append the character itself to the new stringnew_str
. - The result is a string
new_str
with all spaces replaced with underscores.
Replace spaces with underscores using the while loop
We can also use a while
loop to replace spaces with underscores.
Here, is an example:
my_str = "python is awesome"
index = 0
new_str = ""
while index < len(my_str):
if my_str[index] == " ":
new_str += "_"
else:
new_str += my_str[index]
index += 1
print(new_str)
In the above example:
- We initialize the
index
to0
andnew_str
to an empty string. - The
while
loop runs as long as the value of the index is less than the length of the stringmy_str
. - Inside the loop, we use an
if
statement to check if the current character is a space" "
. If it is a space, we add an underscore"_"
to stringnew_str
. Otherwise, we add the current character to stringnew_str
. - The result is a string
new_str
with all spaces replaced with underscores.