Reputation: 21
I would like to do something like as follows:
h=@ , e=( , l=& , o=!
So, in the above example, when you type hello
, it gives back @(&&!
, and vise versa.
(I would perfer it in Python, but it doesn't have to be.)
I would like to make a small utility of this sort. Can anyone help? Thanks!
EDIT: "Basically I would like to be able to assign some letters a unique character. Then, when you run the utility, it asks for your input. Then you type what you want in any order. Using the example above: "hello"="@(&&!" , "elloh"="(&&!@" , "looleh"="&!!&(@" and so forth."
Upvotes: 2
Views: 101
Reputation: 879341
In Python2, you could use str.translate:
import string
table = string.maketrans(
'helo',
'@(&!',)
In [17]: 'hello'.translate(table)
Out[17]: '@(&&!'
In [18]: 'looleh'.translate(table)
Out[18]: '&!!&(@'
Or, you could use unicode.translate
:
In [19]: table = {ord(k):v for k, v in zip(u'helo', u'@(&!')}
In [20]: u'hello'.translate(table)
Out[20]: u'@(&&!'
Lutz Horn's answer shows how you could build a single table which can perform both the forward and backward translation.
In Python3, string.maketrans
has been replaced by bytes.maketrans
:
>>> table = bytes.maketrans(b'helo', b'@(&!')
>>> b'hello'.translate(table)
b'@(&&!'
>>> 'hello'.translate({ord(k):v for k, v in zip('helo', '@(&!')})
'@(&&!'
Upvotes: 7
Reputation:
Use the existing small utility tr
.
In the following example, every uneaven line (1, 3, 5, 7) is input, every even line (2, 4, 6, 8) is output.
$ tr 'helo@(&!' '@(&!helo'
hello
@(&&!
@(&&!
hello
stackoverflow
stack!v(rf&!w
stack!v(rf&!w
stackoverflow
Upvotes: 0