-3

How to replace each letter in a last name by the consecutive letter in the alphabet? I need this script as a masking tool.

Logic for last name: (a change to b, b change to c, ...., z change to a)

Example: John Doe will become John Epf

Input File: names.txt

John yi
kary Strong
Joe Piazza
So  man
scorpionz
  • 35
  • 1
  • 1
  • 7

2 Answers2

1

This is called Caesar's cipher.

Take a look at how it's done here: https://stackoverflow.com/a/8895517/6664393

You'll have change it a little to allow uppercase characters as well:

def caesar(plaintext, shift):
    alphabet_lower = string.ascii_lowercase
    alphabet_upper = string.ascii_uppercase
    alphabet = alphabet_lower + alphabet_upper
    shifted_alphabet_lower = alphabet_lower[shift:] + alphabet_lower[:shift]
    shifted_alphabet_upper = alphabet_upper[shift:] + alphabet_upper[:shift]
    shifted_alphabet = shifted_alphabet_lower + shifted_alphabet_upper
    table = string.maketrans(alphabet, shifted_alphabet)
return plaintext.translate(table)

use shift = 1 to shift by one.

Community
  • 1
  • 1
user357269
  • 1,835
  • 14
  • 40
0

The problem as defined in your question can be solved as follows:

parts = name.split()
parts[1]=''.join([chr((ord(c) - 65 + 1) % 26 + 65)
                  if ord(c) < 91 else
                  chr((ord(c) - 97 + 1) % 26 + 97)
                  for c in parts[1]])
' '.join(parts)

Here, I define the last name as the second word of the string, this of course is a strong assumption, but improving on this is not the main problem in the question.

Shifting the characters is done inside a list comprehension, where each character is processed separately, and first converted to its ASCII code using ord. The ASCII codes of upper case letters are 65-90 (A-Z), and the ASCII codes of lowercase letters are 97-122 (a-z). Therefore, a condition ord(c) < 91 is used to separate the cases. Then, in each case, the ASCII code is converted to a value in the range 0-25, shifted (in the example, incremented by 1), and modulo operation % 26 is used to convert shifted z back into a. The resulting value is then converted back to the proper range for the letter ASCII codes.

Andrzej Pronobis
  • 33,828
  • 17
  • 76
  • 92