0

I'm trying to translate a single integer input to a multiple integer output, and am currently using the transtab function. For instance,

intab3 = "abcdefg"
outtab3 = "ABCDEFG"
trantab3 = maketrans(intab3, outtab3)

is the most basic version of what I'm doing. What I'd like to be able to do is have the input be a single letter and the output be multiple letters. So something like:

intab4 = "abc"
outtab = "yes,no,maybe" 

but commas and quotation marks don't work. It keeps saying :

ValueError: maketrans arguments must have same length

Is there a better function I should be using? Thanks,

4

2 回答 2

1

在 python3 中,该str.translate方法得到了改进,因此它可以正常工作。

>>> intab4 = "abc"
>>> outtab = "yes,no,maybe"
>>> d = {ord(k): v for k, v in zip(intab4, outtab.split(','))}
>>> print(d)
{97: 'yes', 98: 'no', 99: 'maybe'}
>>> 'abcdefg'.translate(d)
'yesnomaybedefg'
于 2013-05-10T02:56:17.233 回答
1

您可以在此处使用字典:

>>> dic = {"a":"yes", "b":"no", "c":"maybe"}
>>> strs = "abcd"
>>> "".join(dic.get(x,x) for x in strs)
'yesnomaybed'
于 2013-05-10T02:46:40.717 回答