简体   繁体   中英

How to replace each letter in a string with a consecutive letter with increasing offset?

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)

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM