Change the letters of a string

I need to write a code that shifts each letter of a string (cipher) a given number (shift) further alphabetically. The code I have written so far is as follows (with an example to test the function):

    def decode(cipher, shift):
        letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        for letter in cipher:
            index = letters.index(letter)
            cipher = cipher.replace(letter, letters[index-shift])
        return cipher
    print decode("LIPPSASVPH", 4)

This almost works, except what happens as the code goes through the cipher, it will change any letter that matches the one it is changing now, so for my example it should return “HELLOWORLD”, but “DELLOWORLD is returned instead” "because the last letter of the encryption is H, and the code previously changed L at the beginning of the encryption to H, so the code changes both values ​​of H to D. Any suggestions on how to make the code run on each letter separately without changing the other letters? Thank you all very much.

+4
5

,

def decode(cipher, shift):
    letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    result = ''
    for letter in cipher:
        index = letters.index(letter)
        result += letters[index - shift]
        # cipher = cipher.replace(letter, letters[index - shift])
    return result
print decode("LIPPSASVPH", 4)
+1

. - :

def decode(cipher, shift):
  result = ""
  letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  for letter in cipher:
      index = letters.index(letter)
      #cipher = cipher.replace(letter, letters[index-shift])
      result += letters[index-shift]
return result
print (decode("LIPPSASVPH", 4))
+1

L, D .. str.replace. - :

def decode(cipher, shift):
    letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    new_cipher = []
    for letter in cipher:
        new_cipher.append(letters[letters.index(letter)-shift])
    return ''.join(new_cipher)

. ''.join().

:

>>> decode("LIPPSASVPH", 4)
'HELLOWORLD'

: (, ):

>>> letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> cipher = 'LIPPSASVPH'
>>> shift = 4
>>> new_cipher = ''.join(letters[letters.index(letter)-shift] for letter in cipher)
+1

, , . . , .

x = "Hello"
y = list(x)
# y is now ['H', 'e', 'l', 'l', 'o']
y[1] = 'i'
# y is now ['H', 'i', 'l', 'l', 'o']
x = str(y)
0

You could have built the result in a new variable, as others had suggested, but my instinct would have to use a completely different approach. I would do a plaintext cipher mapping with maketrans(), and then use translate()to decrypt:

>>> from string import maketrans
>>>
>>> def decode(cipher, shift):
...     letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
...     shift = shift % len(letters)
...     mapping = maketrans(letters[shift:] + letters[:shift], letters)
...     return cipher.translate(mapping)
...
>>> print decode("LIPPSASVPH", 4)
HELLOWORLD
0
source

Source: https://habr.com/ru/post/1669097/


All Articles