How to remove all special characters from a string in Python

3 Answers

0 votes
s = '!Beam- me& ~up, Scotty;.'

s = ''.join(ch for ch in s if ch.isalnum())

print(s)


 
    
 
'''
run:
 
BeammeupScotty

'''

 



answered Apr 14, 2021 by avibootz
0 votes
s = '!Beam- me& ~up, Scotty;.'

s = ''.join(filter(str.isalnum, s)) 

print(s)


 
    
 
'''
run:
 
BeammeupScotty

'''

 



answered Apr 14, 2021 by avibootz
0 votes
import re

s = '!Beam- me& ~up, Scotty;.'

s = re.sub(r"[^a-zA-Z0-9]", "", s)

print(s)


    
 
'''
run:
 
BeammeupScotty

'''

 



answered Apr 14, 2021 by avibootz
...