简体   繁体   中英

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

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 !

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.

from string import maketrans

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

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

this will output:

th3s 3s str3ng 2x1mpl2

Look up the function translate for more info

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM