Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

perl - Character Translation using Python (like the tr command)

Is there a way to do character translation / transliteration (kind of like the tr command) using Python?

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
";  # b b   b.  (because option "d" is used to delete characters not replaced)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See string.translate

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

Note the doc's comments about subtleties in the translation of unicode strings.

And for Python 3, you can use directly:

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

Edit: Since tr is a bit more advanced, also consider using re.sub.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...