0

次のような文字列があります。

string = 'これは 2013 年 2 月 11 日の私のテキストで、このような文字が含まれていました! (例外的)」

これらは、文字列から削除したいシンボルです。

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

私が試したことは次のとおりです。

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

エラーは次のとおりです。

整数が必要です

これを行うのを手伝ってください!

4

3 に答える 3

7

これを試して

>>> 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

また、すでに組み込みの名前または標準ライブラリの一部である変数の名前付けは控えてください。

于 2013-03-08T06:28:09.687 に答える
3

これはどう?また、組み込みモジュールと混同しないように名前を に変更stringしました。sstring

>>> 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
于 2013-03-08T06:27:28.300 に答える
0

より複雑なフィルター基準または他の入力データ型に簡単に拡張できる別の提案:

from itertools import ifilter

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

print "".join(ifilter(isValid, my_string))
于 2013-03-08T08:45:08.903 に答える