Ric*_*eur 39
import string
"abc".translate(string.maketrans("abc", "def")) # => "def"
Run Code Online (Sandbox Code Playgroud)
请注意doc对unicode字符串翻译中细微之处的评论.
编辑:既然tr
有点先进,也可以考虑使用re.sub
.
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 -d
python2.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)