Search code examples
pythonencryptionord

Is there a way to create a list of characters, ord() them to integers, and hex() them to a hex code?


I am a beginner programmer using Python, and I am trying to create encryption software (Beginner). I am looking for something like:

Input: Apple -> A, P, P, L, E -> ord() -> 97,"","","","" -> hex() -> 0x16, "","" ,"" ,""

However, I cannot find a way to translate my characters to integers while accounting for an unknown amount of characters in input.

Sentence = list(input("Enter"))
print(Sentence)
ord_sentence = []
for each in range(len(Sentence)):
    ord_sentence.append(ord(Sentence[]))

This then doesn't work because the argument at the end of Sentence is empty, but I don't know how to make it fill with each individual character. I could try

...
...
while len(ord_sentence) <= len(Sentence)
   ord_sentence.append(ord(sentence[0]))
   ord_sentence.append(ord(sentence[1]))
##Continues on to 1000 to account for unknown input##

But then, I run into INDEX ERROR when the input isn't exactly 1000 characters long, and putting something like:

...
ord_sentence.append(ord(sentence[0]))
if IndexError:
    print(ord_sentence)
    break

Only results in it printing the first digit of the sequence, and then breaking.

Any help would be greatly appreciated! Thank you!!!


Solution

  • I think you need to read about how loops work again. When you iterate over something, the value gets assigned to a variable. In your code, that's each. You never use that variable for anything, but I think it's what you're looking for.

    for each in range(len(Sentence)):
        ord_sentence.append(ord(Sentence[each]))
    

    Iterating over a range and indexing as you're doing here works, but it's not as direct as just iterating on the list directly. You could instead do:

    for each in Sentence:                   # no range, len, each is a character
        ord_sentence.append(ord(each))      # take its ord() directly
    

    Or you could use a list comprehension to build a new list form an old one directly, without a separate loop and a bunch of append calls:

    ord_sentence = [ord(each) for each in Sentence]
    

    While each is the name you've been using in your code, it is better practice to give a more specific name to your variables, that tells you what the value means. In the first version here, where you're iterating over a range, I'd use index, since that's what the number you get is (an index into the list). For the other two, value or character might make more sense, since the value is a single character from the Sentence list. Speacking of that list, its name is a little misleading, as I'd expect a sentence to be a string, or maybe a list of words, not a list of characters (that might have come from more or less than one sentence, e.g. ['f', 'o', 'o'] or ['F', 'o', 'o', '.', ' ', 'B', 'a', 'r', '.']).