使用Python进行字符转换(如tr命令)

发布于 2021-01-29 18:04:27

有没有一种方法可以tr使用 Python 进行字符翻译/音译(类似于命令)?

Perl中的一些示例是:

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)
关注者
0
被浏览
47
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    看到
    string.translate

    import string
    "abc".translate(string.maketrans("abc", "def")) # => "def"
    

    请注意文档中有关unicode字符串翻译中微妙之处的评论。

    对于Python 3,您可以直接使用:

    "abc".translate(str.maketrans("abc", "def"))
    

    编辑:由于tr有点高级,因此也可以考虑使用re.sub



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看