-1
def encrypt(string, new_string):
    i = 0
    if i < len(string):
        if ord(string[i]) > 65 and ord(string[i]) < 97:
            new_string = string[i] + encrypt(string[1:], new_string)

        if ord(string[i]) >= 97 or ord(string[i]) == 32:
            if not(ord(string[i])) == 32:
                x = ord(string[i])
                x = x + 1
                y = chr(x)
                new_string = new_string + y

                new_string = encrypt(string[1:], new_string)

            else:
                new_string = new_string + ' '
                new_string = encrypt(string[1:], new_string)
    return new_string

string = input("Enter a message: \n")
new_string = ''


print("Encrypted message:")
print(encrypt(string, new_string))

If there is more than one uppercase letter, it will output the uppercase letters at the front of the encrypted message.

For example: 'Hello World' becomes 'HWfmmp psme'. However, the output should have been 'Hfmmp Xpsme'

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
pk.
  • 99
  • 3
  • 12

2 Answers2

1

translate can help you to do this kind of conversion.

from string import ascii_lowercase

def encrypt(data):
    transmap = str.maketrans(ascii_lowercase, ascii_lowercase[1:] + ascii_lowercase[0])
    return data.translate(transmap)

value = 'Hello World'
print(encrypt(value))

The result is Hfmmp Wpsme.


It's easy to change the encrypt function to work with a flexible offset.

from string import ascii_lowercase

def encrypt(data, offset=1):
    transmap = str.maketrans(ascii_lowercase, ascii_lowercase[offset:] + ascii_lowercase[0:offset])
    return data.translate(transmap)

value = 'Hello World'
print(encrypt(value, offset=2))
print(encrypt(value, offset=-1))

This will print Hgnnq Wqtnf and Hdkkn Wnqkc.

Matthias
  • 12,873
  • 6
  • 42
  • 48
0
>>> import re
>>> re.sub('[a-z]',lambda x:chr(ord(x.group(0))+1),'Hello World')
'Hfmmp Wpsme'
>>> 
YOU
  • 120,166
  • 34
  • 186
  • 219