使用 Python 进行字符转换(如 tr 命令) [英] Character Translation using Python (like the tr command)
本文介绍了使用 Python 进行字符转换(如 tr 命令)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法使用 Python 进行字符翻译/音译(有点像 tr
命令)?
Is there a way to do character translation / transliteration (kind of like the tr
command) using Python?
Perl 中的一些示例是:
Some examples in Perl would be:
my $string = "some fields";
$string =~ tr/dies/eaid/;
print $string; # domi failed
$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "$string\n"; # b b b. (because option "d" is used to delete characters not replaced)
推荐答案
import string
"abc".translate(string.maketrans("abc", "def")) # => "def"
请注意文档对 unicode 字符串翻译中微妙之处的评论.
Note the doc's comments about subtleties in the translation of unicode strings.
而对于 Python 3,您可以直接使用:
And for Python 3, you can use directly:
"abc".translate(str.maketrans("abc", "def"))
由于 tr
更高级一些,还可以考虑使用 re.sub
.
Since tr
is a bit more advanced, also consider using re.sub
.
这篇关于使用 Python 进行字符转换(如 tr 命令)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文