iMohammad
iMohammad

Reputation: 83

Remove space and dash in string python

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

Answers (5)

red798
red798

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

petezurich
petezurich

Reputation: 10184

Try this:

import re

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

Upvotes: 1

U13-Forward
U13-Forward

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

Rohit-Pandey
Rohit-Pandey

Reputation: 2159

You can use .isalnum()

''.join(e for e in a if e.isalnum()) 

Upvotes: 2

Mehrdad Pedramfar
Mehrdad Pedramfar

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

Related Questions