1)如何用数字1替换大写字母A和小写字母“a”?
encrp_key = input('Enter the number 1' )
msg = input('Enter some lowercase and some uppercase')
if encrp_key == 1:
new_msg = msg.replace('a ','1').replace('e','2')\
.replace('i','3').replace('o','4').replace('u','5')
## if user types 'ABBSAS acbdcd '
# how do i replace 'A' and 'a' with 1 , E and e with 2 and
# I and i with 3 and so on.
答案 0 :(得分:2)
>>> tbl = {ord(c): str(i) for i, ch in enumerate('aeiou', 1)
for c in [ch, ch.upper()]}
>>> # OR tbl = str.maketrans('aeiouAEIOU', '1234512345')
>>> tbl # Make a mapping of old characters to new characters
{97: '1', 101: '2', 73: '3', 65: '1', 105: '3', 79: '4', 111: '4',
117: '5', 85: '5', 69: '2'}
>>> 'Hello world'.translate(tbl)
'H2ll4 w4rld'
答案 1 :(得分:1)
制作一张包含maketrans
的翻译表。相应的元素被映射在一起。
from string import maketrans
tbl = maketrans('aAeEiIoOuU','1122334455')
print "aAeEiIoOuU".translate(tbl)
输出:
1122334455
或者你可以这样做:
from string import maketrans
tbl = maketrans('aeiou','12345')
print "aAeEiIoOuU".lower().translate(tbl)
输出:
1122334455
from string import maketrans
tbl = maketrans('aAeEiIoOuU','1122334455')
msg = input('Enter a sentence: ')
enc_key = int(input('Enter 1 for encryption, 0 for orignal text: '))
if enc_key == 1:
print(msg.translate(tbl))
else:
print(msg)
输出:
Enter a sentence: I want to encrypt My MeSSages
Enter 1 for encryption, 0 for orignal text: 1
3 w1nt t4 2ncrypt My M2SS1g2s
答案 2 :(得分:0)
另一种方法:
st = "abbrwerewrfUIONIYBEWw"
d = {v: str(i+1) for i, v in enumerate(list("aeiou"))}
for v in st:
v = v.lower()
if v in d:
st = st.replace(v, d[v])