0

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!

dda
  • 6,030
  • 2
  • 25
  • 34
MHS
  • 2,260
  • 11
  • 31
  • 45
  • 1
    http://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python this may be helpfull!! – JK Patel Mar 08 '13 at 06:32

3 Answers3

7

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.

Volatility
  • 31,232
  • 10
  • 80
  • 89
3

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
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • I would have suggested something similar; two minor points: the name "listofsymbols" could be sharpened to "filtersymbols" and the list notation is a bit clumsy, since a simple string also works. – guidot Mar 08 '13 at 08:10
  • @guidot. One, names do not matter (with the exceptions of getting mixed up with built-in functions). And strings are immutable, so how would you do your second suggestion? – TerryA Mar 08 '13 at 08:17
  • filtersymbols IS immutable (the string notation also prevents errors like '@ ' instead of '@') since only used for look-up; and while names don't matter for compilers they do for humans. – guidot Mar 08 '13 at 08:36
0

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))
guidot
  • 5,095
  • 2
  • 25
  • 37