我有一个很好的小方法从字符串中删除控制字符.不幸的是,它在Python 2.6中不起作用(仅在Python 3.1中).它指出:
Run Code Online (Sandbox Code Playgroud)mpa = str.maketrans(dict.fromkeys(control_chars))AttributeError:类型对象'str'没有属性'maketrans'
def removeControlCharacters(line):
control_chars = (chr(i) for i in range(32))
mpa = str.maketrans(dict.fromkeys(control_chars))
return line.translate(mpa)
Run Code Online (Sandbox Code Playgroud)
怎么改写?
对于此实例,不需要maketrans字节字符串或Unicode字符串:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> delete_chars=''.join(chr(i) for i in xrange(32))
>>> '\x00abc\x01def\x1fg'.translate(None,delete_chars)
'abcdefg'
Run Code Online (Sandbox Code Playgroud)
要么:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> delete_chars = dict.fromkeys(range(32))
>>> u'\x00abc\x01def\x1fg'.translate(delete_chars)
u'abcdefg'
Run Code Online (Sandbox Code Playgroud)
甚至在Python 3中:
Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> delete_chars = dict.fromkeys(range(32))
>>> '\x00abc\x01def\x1fg'.translate(delete_chars)
'abcdefg'
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅help(str.translate)和help(unicode.translate)(在Python2中).
| 归档时间: |
|
| 查看次数: |
8872 次 |
| 最近记录: |