Replace certain characters in an input-string with pre-defined replacement characters (python 3)

时间:2016-02-12 19:21:26

标签: python

I want to write a program that encodes a word you typed into the console like this:

If You write an A for example it will be replaced with a Z or you type T and get a U.

Example:

A --> Z  
T --> U 
H --> F 

If it's possible can you tell me how to change the word you typed in the console?

Still need help can't figure out how to do it !

3 个答案:

答案 0 :(得分:6)

That's easy, just define a dictionary which maps characters to their replacement.

>>> replacers = {'A':'Z', 'T':'U', 'H':'F'}
>>> inp = raw_input()
A T H X
>>> ''.join(replacers.get(c, c) for c in inp)
'Z U F X'

I don't know where exactly you want to go and whether case-sensitivity matters, or if there's a more general rule to determine the replacement character that you did not tell us - but this should get you started.

edit: an explanation was requested:

(replacers.get(c, c) for c in inp) is a generator which spits out the following items for the example input:

>>> [replacers.get(c, c) for c in inp]
['Z', ' ', 'U', ' ', 'F', ' ', 'X']

For each character c in the input string inp we ge the replacement character from the replacers dictionary, or the character itself if it cannot be found in the dictionary. The default value is the second argument passed to replacers.get.

Finally, ''.join(some_iterable) builds a string from all the items of an iterable (in our case, the generator), glueing them together with the string join is being called on in between. Example:

>>> 'x'.join(['a', 'b', 'c'])
'axbxc'

In our case, the string is empty, which has the effect of simply concatenating all the items in the iterable.

答案 1 :(得分:0)

from string import maketrans

orginalCharacters = "aeiou"
encodedCharacters = "12345"
trantab = maketrans(orginalCharacters, encodedCharacters)

text = "this is string example";
print text.translate(trantab)

这将输出:

th3s 3s str3ng 2x1mpl2

查找功能翻译以获取更多信息

答案 2 :(得分:-1)

timgeb has a great solution; alternatively, you could also use what's on this page of the docs and use a for loop to assign a random integer to each letter, and store it in a dictionary (see randint).

This would be more helpful if you want it to change every time you run your program.