Search code snippets, questions, articles...

Replace all spaces with hyphens in Python

Here, we are going to describe to replace all the spaces with hyphens. We will also convert the result to lowercase letters. You can take the reference of code examples explained in this post.
# create a string
my_str = "Making projects in Python is fun"

# replace space with hyphen
hyphen_str = my_str.replace(" ", '-')

# print the output
print(hyphen_str)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

Making-projects-in-Python-is-fun

Example 2: Also convert the characters to lowercase along with replacing spaces with hyphens

# create a string
my_str = "Making projects in Python is fun"

# replace space with hyphen
hyphen_str = my_str.replace(" ", '-').lower()

# print the output
print(hyphen_str)

Output

making-projects-in-python-is-fun

Replace whitespaces with underscores in Python

my_str = "we are programmers"

result = my_str.replace(' ', '_')

print(result.lower())

# -> we_are_programmers

Method 2: Use regex to replace spaces with hyphens

We can also use regular expressions to replace the spaces with hyphens. For example, if you are generating link text from a title then you need to remove the spaces and use hyphens or underscore in place of them.

re.sub('\s', '-', str_var)

Code Example

import re

# define a string
my_str = "Making projects in Python is fun"

# replace space with hyphen using regex
result = re.sub('\s', '-', my_str)

# print the output
print(result)

Output

Making-projects-in-Python-is-fun

Method 3: Use join() and split() function to replace whitespace with hyphen

We will be using join() and split() functions here that will remove all the whitespaces from the string and place hyphens in place of them. You can check the below example to understand it.

title = "we can make programs easily in python"

result = "-".join(title.split())

print(result)

Output

we-can-make-programs-easily-in-python
import re

# define a string
my_str = "Learn and Grow on Devsheet"

# replace space with hyphen using regex
result = re.sub('\s', '_', my_str)

# print the output
print(result.lower())

# -> learn_and_grow_on_devsheet
We can use the above code example to replace all the spaces with hyphens. We are using regex here. We can also do that using replace() function if you do not want to use the regular expressions.
Was this helpful?
0 Comments