This can be done without regex:
>>> string = "Special $#! characters spaces 888323" >>>
''.join(e
for e in string
if e.isalnum())
'Specialcharactersspaces888323'
S.isalnum() - > bool
Return True
if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
S.isalnum() - > bool
Return True
if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
Here is a regex to match a string of characters that are not a letters or numbers:
[ ^ A - Za - z0 - 9] +
Here is the Python command to do a regex substitution:
re.sub('[^A-Za-z0-9]+', '', mystring)
Shorter way :
import re
cleanString = re.sub('\W+', '', string)
I timed the provided answers.
import re
re.sub('\W+', '', string)
Example 1
'.join(e for e in string if e.isalnum())
Example 2
import re
re.sub('[^A-Za-z0-9]+', '', string)
I think just filter(str.isalnum, string)
works
In[20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'
In Python3, filter( )
function would return an itertable object (instead of string unlike in above). One has to join back to get a string from itertable:
''.join(filter(str.isalnum, string))
or to pass list
in join use (not sure but can be fast a bit)
''.join([ * filter(str.isalnum, string)])
October 26, 2021March 8, 2022
Let’s see what this example looks like:
# Remove Special Characters from a String Using.isalnum() text = 'datagy -- is. great!' new_text = '' for character in text: if character.isalnum(): new_text += character print(new_text) # Returns: datagyisgreat
Let’s see what this looks like in Python:
# Remove Special Characters from a String Using re.sub() import re text = 'datagy -- is. great!' new_text = re.sub(r "[^a-zA-Z0-9 ]", "", text) print(new_text) # Returns: datagy is great
Let’s try this out in Python:
# Remove Special Characters from a String Using re.sub() import re text = 'datagy -- is. great!' new_text = ''.join(filter(str.isalnum, text)) print(new_text) # Returns: datagyisgreat
It removed all the special characters from the string.,It also removed all the special characters from the string.,It also removed all the spcecial characters from the string.,In python, string.punctuation from string module contains all the special characters i.e.
In python, string.punctuation from string module contains all the special characters i.e.
r ""
"!"
#$ % & '()*+,-./:;<=>[email protected][\]^_`{|}~"""
import string import re sample_str = "Test&[88]%%$$$#$%-+String" # Create a regex pattern to match all special characters in string pattern = r '[' + string.punctuation + ']' # Remove special characters from the string sample_str = re.sub(pattern, '', sample_str) print(sample_str)
Output:
Test88String
Using list comprehension, iterate over all the characters of string one by one and skip characters non alphanumeric characters. It returns a list of filtered characters. Combine these remaining characters using join() and assign it back to same variable. It will give an effect that we have deleted all special characters from the string. For example,
sample_str = "Test&[88]%%$$$#$%-+String" # Remove special characters from a string sample_str = ''.join(item for item in sample_str if item.isalnum()) print(sample_str)
For example,
sample_str = "Test&[88]%%$$$#$%-+String" # Remove special characters from a string sample_str = ''.join(filter(str.isalnum, sample_str)) print(sample_str)
Remote Work 2022 , Remote Work 2022
Syntax of replace():
string.replace(old character, new character, count)
Code to remove a character from string in Python using replace():
s = "flexible!"
s2 = string.replace("b", "p")
print(s2)
// Output - "flexiple!"
//Code to remove a character
s3 = string.replace("!", "")
print(s3)
//Output - "flexiple"
Syntax of translate():
string.translate(table)
Code to remove character from string using translate():
s = 'flexiple!'
s1 = s.translate({
ord('!'): None
})
print(s1)
#Output - "flexiple"
The replace() method is a built-in functionality offered in Python. It replaces all the occurrences of the old substring with the new substring. One can use replace() inside a loop to check for a special_char and then replace it with the empty string hence removing it.,Here, we will develop a program to remove special characters from the string in Python. If the string was “[email protected]” then the result in the string will be “KnowProgram”. We will discuss how to remove all special characters from the given string using Regular Expression, replace(), translate(), join(), filter() method, and str.isalnum() function.,In the previous program, we used the join() method but in this program, we are using the join(), filter(), and lambda() function to remove all special characters from a string. The filter() method constructs an iterator from elements of an iterable for which a function returns true.,We are using the join() method to remove special characters. In the generator function, we specify the logic to ignore the characters in special_char and hence constructing a new string free from special characters.
We will first be importing Regular Expression (RegEx module). The regular expression will automatically remove the special characters from the string. The regular expression for this will be [^a-zA-Z0-9], where ^ represents any character except the characters in the brackets.
# Python program to remove all special characters from string # importing RegEx module import re # take string string = input('Enter any string: ') # using regular expression to remove special characters new_string = re.sub(r '[^a-zA-Z0-9]', '', string) # print string without special characters print('New string:', new_string)
The replace() method is a built-in functionality offered in Python. It replaces all the occurrences of the old substring with the new substring. One can use replace() inside a loop to check for a special_char and then replace it with the empty string hence removing it.
# Python program to remove all special characters from string
# take string
string = input('Enter any string: ')
# initializing special characters
special_char = '@_!#$%^&*()<>?/\|}{~:;[]'
# using replace() to remove special characters
for i in special_char:
string = string.replace(i, '')
# print string without special characters
print('New string:', string)
We are using the join() method to remove special characters. In the generator function, we specify the logic to ignore the characters in special_char and hence constructing a new string free from special characters.
# Python program to remove all special characters from string
# take string
string = input('Enter any string: ')
# initializing special characters
special_char = '@_!#$%^&*()<>?/\|}{~:;[]'
# using join() + generator to remove special characters
new_string = ''.join(x
for x in string
if not x in special_char)
# print string without special characters
print('New string:', new_string)
This python program also performs the same task but in different ways. In this program, we are also using str.isalnum() function. The str.isalnum() method returns True if the characters are alphanumeric characters, meaning no special characters in the string. It will return False if there are any special characters in the string.
# Python program to remove all special characters from string # take string string = input('Enter any string: ') # using str.isalnum() function to remove special characters new_string = ''.join(filter(str.isalnum, string)) # print string without special characters print('New string:', new_string)
The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table. Use the maketrans() method to create a mapping table. If a character is not specified in the dictionary/table, the character will not be replaced. We can translate each special_char to an empty string and get a filtered string.
# Python program to remove all special characters from string # importing string function import string # take string test_string = input('Enter any string: ') # using translate() to remove special characters new_string = test_string.translate(str.maketrans('', '', string.punctuation)) # print string without special characters print('New string:', new_string)