Reputation: 23
Suppose the word is "CAT"
and I want the output to be "DCW"
. Where the C
changes to the next letter D
and the A
changes into the second next letter from A
to C
and the T
changes into the third next letter from T
to W
.
I am on the first step here:
a = input("Enter a letter: ")
a = chr(ord(a) + 1)
print(a)
Upvotes: 1
Views: 68
Reputation: 18126
You need to loop over the word:
word = 'CAT'
result = ''
for i, a in enumerate(word,1):
result += chr(ord(a) + i)
print(result)
# alternatively, same loop as list comprehension
print(''.join(chr(ord(a) + i) for i, a in enumerate(word,1)))
Out:
DCW
DCW
Upvotes: 1
Reputation: 1659
try this :
import string
a =input("Enter a letter: ")
r=''
for i,e in enumerate(a,1):
r=r+string.ascii_lowercase[string.ascii_lowercase.index(e.lower())+i]
print(r.upper())
or in one line like this :
print(''.join(list(string.ascii_lowercase[string.ascii_lowercase.index(e.lower())+i] for i,e in enumerate(a,1) )).upper())
Note: in Python 2, string.ascii_lowercase
is string.lowercase
.
Upvotes: 0
Reputation: 74
What you are looking for is called Caesar cypher, but the offset changes with the character's position:
def encrypt(text):
result = ""
for i in range(len(text)):
char = text[i]
if (char.isupper()):
result += chr((ord(char) -65) % 26 + 65 + i + 1)
else:
result += chr((ord(char) - 97) % 26 + 97 + i + 1)
return result
print(encrypt(input()))
Source: https://www.tutorialspoint.com/cryptography_with_python/cryptography_with_python_caesar_cipher.htm
Upvotes: 0