Search code examples
pythonasciivigenere

Conversion of alphabet into numerical values


I am trying to decode a Vigenere cipher in python knowing the ciphertext and plaintext

I have a string of text in this form 'SDFJNKSJDFOSNFDF'. I want to convert each letter to a number so I'm able to decode the text, i.e. A to 1, B to 2...

The idea I had was to convert this using ascii, checking what the capital letters correspond to would mean I could deduct this, I don't have an example code that hasn't worked, I've written some details that will hopefully make my idea easier to understand:

My string looks like this:

string = 'SDFJNKSJDFOSN'

However as I am working with a Vigenere cipher, I know my blocklength is six so I also have

blocks = ['SDFJNK', 'SJDFOS', 'N']

I don't know whether it would be easier to convert to numbers then break into blocks or the other way around? My thoughts were to use ascii text, for example if in ascii D = 35 as this is inclusive of multiple characters, I could use this to rewrite all numbers as whatever their ascii is - 31 so D = 4 and all other letters would follow suit

Apologies for the lack of written examples of what I mean but other questions on here have so much variation I don't know where to start, ideally the output would look something like this:

output:
['19,4,6,10,14,11','19,10,4,6,15,19','15']

OR

output:
['19,4,6,10,14,11,19,10,4,6,15,19,15']

Solution

  • Use ord(character) to get the value for each letter

    string = 'SDFJNKSJDFOSN'
    count = 0
    for letter in string:
        print(f'{ord(letter)=}')
    
    print('\nOr outputs as a list\n')
    
    letter_codes = []
    for letter in string:
        letter_codes.append(ord(letter))
    print(letter_codes)
    

    output

    ord(letter)=83
    ord(letter)=68
    ord(letter)=70
    ord(letter)=74
    ord(letter)=78
    ord(letter)=75
    ord(letter)=83
    ord(letter)=74
    ord(letter)=68
    ord(letter)=70
    ord(letter)=79
    ord(letter)=83
    ord(letter)=78
    
    Or outputs as a list
    
    [83, 68, 70, 74, 78, 75, 83, 74, 68, 70, 79, 83