To remove special characters from a string in Python, you can use the re.sub() function with a regular expression pattern.
In this example,
str1
with a value of "Hello! World!"
.re.sub()
function with a regular expression pattern r'[^a-zA-Z0-9 ]'
to replace all non-alphanumeric characters and spaces with an empty string.str1
.import re
str1 = "Hello! World!"
str1 = re.sub(r'[^a-zA-Z0-9 ]', '', str1)
print('Modified string:', str1)
Modified string: Hello World
In this example,
str2
with a value of "apple@banana"
.re.sub()
function with a regular expression pattern r'[^a-zA-Z0-9 ]'
to replace all non-alphanumeric characters and spaces with an empty string.str2
.import re
str2 = "apple@banana"
str2 = re.sub(r'[^a-zA-Z0-9 ]', '', str2)
print('Modified string:', str2)
Modified string: applebanana
In this tutorial, we learned How to Remove Special Characters from a String in Python language with well detailed examples.