在Python中,如何用一个数字替换相同的小写字母和大写字母?

2024-04-20 11:14:05 发布

您现在位置:Python中文网/ 问答频道 /正文

1)如何将大写字母A和小写字母“A”替换为数字1?在

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.

Tags: andthekeynumberinputifwithmsg
3条回答

使用^{}

>>> 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'

只是另一种方法:

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])

maketrans生成翻译表。相应的元素被映射到一起。在

from string import maketrans

tbl = maketrans('aAeEiIoOuU','1122334455')
print "aAeEiIoOuU".translate(tbl)

输出:

^{pr2}$

或者你可以这样做:

from string import maketrans

tbl = maketrans('aeiou','12345')
print "aAeEiIoOuU".lower().translate(tbl)

输出:

^{pr2}$
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

相关问题 更多 >