使用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 个回答
-
import string "abc".translate(string.maketrans("abc", "def")) # => "def"
请注意文档中有关unicode字符串翻译中微妙之处的评论。
对于Python 3,您可以直接使用:
"abc".translate(str.maketrans("abc", "def"))
编辑:由于
tr
有点高级,因此也可以考虑使用re.sub
。