Pognas Sangop
Pognas Sangop

Reputation: 1

Single integer to multiple integer translation in Python

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,

Upvotes: 0

Views: 63

Answers (2)

wim
wim

Reputation: 363083

In python3, the str.translate method was improved so this just works.

>>> 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'

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251051

You can use a dict here:

>>> dic = {"a":"yes", "b":"no", "c":"maybe"}
>>> strs = "abcd"
>>> "".join(dic.get(x,x) for x in strs)
'yesnomaybed'

Upvotes: 1

Related Questions