MHS
MHS

Reputation: 2350

How to remove specific symbols from a text using python?

I have a string like this:

string = 'This is my text of 2013-02-11, & it contained characters like this! (Exceptional)'

These are the symbols I want to remove from my String.

!, @, #, %, ^, &, *, (, ), _, +, =, `, /

What I have tried is:

listofsymbols = ['!', '@', '#', '%', '^', '&', '*', '(', ')', '_', '+', '=', '`', '/']
exceptionals = set(chr(e) for e in listofsymbols)
string.translate(None,exceptionals)

The error is:

an integer is required

Please help me doing this!

Upvotes: 0

Views: 310

Answers (3)

guidot
guidot

Reputation: 5333

Another proposal, easily expandable to more complex filter criteria or other input data type:

from itertools import ifilter

def isValid(c): return c not in "!@#%^&*()_+=`/"

print "".join(ifilter(isValid, my_string))

Upvotes: 0

Volatility
Volatility

Reputation: 32300

Try this

>>> my_str = 'This is my text of 2013-02-11, & it contained characters like this! (Exceptional)'
>>> my_str.translate(None, '!@#%^&*()_+=`/')
This is my text of 2013-02-11,  it contained characters like this Exceptional

Also, please refrain from naming variables that are already built-in names or part of the standard library.

Upvotes: 7

TerryA
TerryA

Reputation: 59984

How about this? I've also renamed string to s to avoid it getting mixed up with the built-in module string.

>>> s = 'This is my text of 2013-02-11, & it contained characters like this! (Exceptional)'
>>> listofsymbols = ['!', '@', '#', '%', '^', '&', '*', '(', ')', '_', '+', '=', '`', '/']
>>> print ''.join([i for i in s if i not in listofsymbols])
This is my text of 2013-02-11,  it contained characters like this Exceptional

Upvotes: 3

Related Questions