Reputation: 83
I have a string and want to remove all space and dash and underline... I want to output is a string A to Z and 0 to 9. my version is Python3 for example :
input:
fafaf fadfa fafa fa-fa faf_afa@gs!
output:
fafaffadfafafafafafafafags
What should I do? Thanks
Upvotes: 2
Views: 3409
Reputation: 21
If you want another option:
s='fafaf fadfa fafa fa-fa faf_afa@gs!'
s.translate(str.maketrans('', '','_-@ !'))
Output:
'fafaffadfafafafafafafafags'
The third argument of str.maketrans(), it must be a string, whose characters will be mapped to None in the result. That means they will be deleted.
And the documents: str.maketrans() and str.translate()
Upvotes: 1
Reputation: 10184
Try this:
import re
letters_only = re.sub("[^a-zA-Z0-9]", "", your_string)
Upvotes: 1
Reputation: 71570
@Rohit has a good answer if if you want it faster do a list comprehension:
print(''.join([i for i in s if i.isalnum()]))
Demo:
s='fafaf fadfa fafa fa-fa faf_afa@gs!'
print(''.join([i for i in s if i.isalnum()]))
Output:
fafaffadfafafafafafafafags
Upvotes: 2
Reputation: 11073
Try this:
import re
input_ = 'fafaf fadfa fafa fa-fa faf_afa@gs!'
input_ = re.sub('[^0-9a-zA-Z]+', '', input_)
Upvotes: 5