使用Python进行字符翻译(如tr命令)

hha*_*fez 42 python

有没有办法使用python进行字符翻译(有点像tr命令)

Ric*_*eur 39

看到 string.translate

import string
"abc".translate(string.maketrans("abc", "def")) # => "def"
Run Code Online (Sandbox Code Playgroud)

请注意doc对unicode字符串翻译中细微之处的评论.

编辑:既然tr有点先进,也可以考虑使用re.sub.

  • 对于python3,`'module'对象没有属性'maketrans'.直接使用`"abc".translate(str.maketrans("abc","def"))` (11认同)

Pio*_*pla 24

如果您使用的是python3,则翻译的详细程度较低:

>>> 'abc'.translate(str.maketrans('ac','xy'))
'xby'
Run Code Online (Sandbox Code Playgroud)

啊..而且还有相当于tr -d:

>>> "abc".translate(str.maketrans('','','b'))
'ac' 
Run Code Online (Sandbox Code Playgroud)

对于tr -dpython2.x,使用另一个参数来转换函数:

>>> "abc".translate(None, 'b')
'ac'
Run Code Online (Sandbox Code Playgroud)


小智 5

我开发了python-tr,实现了tr算法.我们来试试吧.

安装:

$ pip install python-tr
Run Code Online (Sandbox Code Playgroud)

例:

>>> from tr import tr
>>> tr('bn', 'cr', 'bunny')
'curry'
>>> tr('n', '', 'bunny', 'd')
'buy'
>>> tr('n', 'u', 'bunny', 'c')
'uunnu'
>>> tr('n', '', 'bunny', 's')
'buny'
>>> tr('bn', '', 'bunny', 'cd')
'bnn'
>>> tr('bn', 'cr', 'bunny', 'cs')
'brnnr'
>>> tr('bn', 'cr', 'bunny', 'ds')
'uy'
Run Code Online (Sandbox Code Playgroud)