Python 翻译多个字符 [英] Python translate with multiple characters

查看:38
本文介绍了Python 翻译多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 3.3.3 中创建一个程序,该程序将接受一个字符串,然后将其转换为数字 (1-26)

我知道如何处理一位数而不是 2 位

translist = str.maketrans("123456789", "ABCDEFGHI")

有没有办法做到这一点

解决方案

str.translate() 你不能为所欲为;仅适用于一对一替换.您正在尝试用两个不同的字符替换一个字符.

您可以改用正则表达式:

re.sub('[A-Z]', lambda m: str(ord(m.group()) - 64), inputstring)

这需要每个字母的 ASCII 代码点并减去 64(A 在 ASCII 标准中是 65).

请注意,这可能会导致一些令人困惑的模棱两可的解释:

<预><代码>>>>进口重新>>>inputstring = 'FOO BAR BAZ'>>>re.sub('[A-Z]', lambda m: str(ord(m.group()) - 64), inputstring)'61515 2118 2126'

第一组数字是 6 1 5 1 5 还是 6 15 15 ?您可能想要 0-pad 您的数字:

re.sub('[A-Z]', lambda m: format(ord(m.group()) - 64, '02d'), inputstring)

产生:

<预><代码>>>>re.sub('[A-Z]', lambda m: format(ord(m.group()) - 64, '02d'), inputstring)'061515 020118 020126'

I am trying to create a program in python 3.3.3 that will take a string then turn it into numbers (1-26)

I know how to do it for one digit but not 2

translist = str.maketrans("123456789", "ABCDEFGHI")

Is there a way to do this

解决方案

You cannot do what you want with str.translate(); that only works for one-on-one replacements. You are trying to replace one character with two different characters here.

You could use a regular expression instead:

re.sub('[A-Z]', lambda m: str(ord(m.group()) - 64), inputstring)

This takes the ASCII codepoint of each letter and subtracts 64 (A is 65 in the ASCII standard).

Note that this can lead to some confusing ambiguous interpretations:

>>> import re
>>> inputstring = 'FOO BAR BAZ'
>>> re.sub('[A-Z]', lambda m: str(ord(m.group()) - 64), inputstring)
'61515 2118 2126'

Is that 6 1 5 1 5 or 6 15 15 for the first set of numbers? You may want to 0-pad your digits:

re.sub('[A-Z]', lambda m: format(ord(m.group()) - 64, '02d'), inputstring)

which produces:

>>> re.sub('[A-Z]', lambda m: format(ord(m.group()) - 64, '02d'), inputstring)
'061515 020118 020126'

这篇关于Python 翻译多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆