Borislav Hadzhiev
Tue Jun 21 2022·2 min read
Photo by Kate Trifo
To replace spaces with underscores in Python:
replace()
method on the string.replace()
method will return a string with all spaces replaced by
underscores.my_str = 'one two three' result = my_str.replace(' ', '_') print(result) # 👉️ 'one_two_three'
We used the str.replace()
method to replace spaces with underscores in a
string.
The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.
The method takes the following parameters:
Name | Description |
---|---|
old | The substring we want to replace in the string |
new | The replacement for each occurrence of old |
count | Only the first count occurrences are replaced (optional) |
If you need to replace all whitespace characters in a string with underscores,
use the re.sub()
method.
To replace spaces with underscores:
re
module from the standard library.re.sub()
method to replace all whitespace characters with
underscores.import re my_str = 'one two three' result = re.sub(r"\s+", '-', my_str) print(result) # 👉️ 'one_two_three'
The re.sub method returns a new string that is obtained by replacing the occurrences of the pattern with the provided replacement.
The \s
character matches unicode whitespace characters like [ \t\n\r\f\v]
.
The plus +
is used to match the preceding character (whitespace) 1 or more
times.
str.join()
and str.split()
methods.To replace spaces with underscores:
str.split()
method to split the string on each whitespace
character.join()
method on a string containing an underscore.join
method will join the words with an underscore separator.my_str = 'one two three' result = '_'.join(my_str.split()) print(my_str.split()) print(result) # 👉️ 'one_two_three'
We used the str.split()
method to split the string on each whitespace
character.
my_str = 'one two three' # 👇️ ['one', 'two', 'three'] print(my_str.split())
The str.split() method splits the original string into a list of substrings using a delimiter.
If a separator is not provided, the method regards consecutive whitespace characters as a single separator.
my_str = 'one two three' # 👇️ ['one', 'two', 'three'] print(my_str.split())
The last step is to use the str.join
method to join the list of words with an
underscore separator.
my_str = 'one two three' result = '_'.join(my_str.split()) print(result) # 👉️ 'one_two_three'
The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.
The string the method is called on is used as the separator between elements.