# 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)
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
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
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
0 Comments