0

1)How do I replace uppercase A and lowercase 'a' with number 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.

3 Answers3

3

Using str.translate:

>>> 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'
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Can show me to do in a simple way without using for loop or dictionary . Just using replace() and if else? I am a beginner. – rajiv sharma Jan 25 '17 at 14:56
  • @rajivsharma Without using a loop or a dictionary, you're mostly relegated to what you've already done (i.e. using a lot of `str.replace` methods). Not too many of the answers here - while they're great and very Pythonic - are necessarily "beginner." – blacksite Jan 25 '17 at 15:04
1

Make a translation table with maketrans. Corresponding elements are mapped together.

from string import maketrans

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

Output:

1122334455

Or you can do it like so:

from string import maketrans

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

Output:

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) 

Output:

Enter a sentence: I want to encrypt My MeSSages
Enter 1 for encryption, 0 for orignal text: 1
3 w1nt t4 2ncrypt My M2SS1g2s
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
0

Just another approach:

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])
petruz
  • 545
  • 3
  • 13