Reputation: 165
I'm wondering how you can write an algorithm to switch multiple letters at once. What I am seeking is a way to change each (left-hand typing) Q or W or E or R or T in a (right-hand typing) Y or U or I or O or P without messing with the white spaces or capitalisation (actually use of the shift key) of a text and this as a 'mirror' along the entire keyboard (so it also includes punctuation signs).
Anyway, I'm going off topic. If I only would know how to change specific signs to other specific signs in a strong without heaving to write a spaghetti code with 112 if/elif statements (total signs I have to swap * 4, because of vice versa and shift values)/
Is it possible to get all the signs in a string and switch them with other signs in another while still not messing up the white spaces in the sentence?
for i in sentence:
if i == 'Q':
i = 'Y'
elif i == 'q':
i = 'y'
elif i == # etc...
Would be far too long.
Upvotes: 0
Views: 70
Reputation: 304225
>>> import string
>>> t = string.maketrans("Qq","Yy")
>>> "QqQq".translate(t)
'YyYy'
Upvotes: 4
Reputation: 250991
Use a dictionary:
In [7]: strs="aAb BcD"
In [8]: dic={'a':'q','A':'w','b':'E','B':'r','c':'A','D':'y'}
In [9]: "".join(dic.get(x,x) for x in strs)
Out[9]: 'qwE rAy'
Upvotes: 1