简体   繁体   中英

Trying to transcribe using ascii values using ord and chr

Trying to make an encrypter that shifts ascii values of each character in a message by the value of a corresponding character in a password - Output always results in either a single character or a string index out of range error:

msg = input()
pw = input()
pwN = 0
msgN = 0

for i in msg:
    newmsg =""
    nchar = chr(ord(msg[msgN]) + ord(pw[pwN]))
    pwN += 1
    msgN += 1
    if pwN > len(pw):
        pwN = 0
    newmsg += nchar

print (newmsg)

Running it in this form results in a single character rather than a message length string in some cases, and in others gives me this error:

Traceback (most recent call last):
  File "file", line 8, in <module>
    nchar = str(chr(ord(msg[msgN]) + ord(pw[pwN])))
IndexError: string index out of range

I can't figure out what I'm missing.

The issue is that you're setting newmsg to the empty string in each loop. Moving newmsg = "" before the for loop should fix the issue of single characters, although figuring out the out of range error is difficult because of your manual increasing of several indices while also iterating over msg .

I would suggest taking a look at the iteration features Python offers. You are technically iterating over msg , but never actually use i , instead relying solely on indices. A more pythonic way to solve this might be as follows:

from itertools import cycle

msg = input()
pw = input()

newmsg = ""
for mchar, pwchar in zip(msg, cycle(pw)): # cycle loops the password so that abc becomes abcabcabc...
    newmsg += chr(ord(mchar) + ord(pwchar))
print(newmsg)

if you want to stick to the loop. I would even use a generator expression to make it

from itertools import cycle

msg = input()
pw = input()

newmsg = "".join(chr(ord(mchar) + ord(pwchar)) for mchar, pwchar in zip(msg, cycle(pw)))
print(newmsg)

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