Bdfy
Bdfy

Reputation: 24699

How to filter symbols in string by mask?

How to filter symbols in string by mask ?

For example, I have simple string:

"tes!@#$%^&*(())___+t" "test1" "test3N"

How to delete symbols NOT IN "a-zA-Z", for example ?

Upvotes: 0

Views: 1723

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123420

Simple, use a negative character class in regex:

import re

re.sub('[^a-zA-Z]', '', inputstring)

[....] denotes a character class. Normally, anything in the class matches. By adding the ^ caret at the start you negate the class; anything not in the class matches.

Result:

>>> import re
>>> re.sub('[^a-zA-Z]', '', '"tes!@#$%^&*(())___+t" "test1" "test3N"')
'testtesttestN'

Upvotes: 5

Related Questions