-2

I want to decrypt the code via a txt file. But I got an error ord () expected a character, but a string of length 586 was found. Any suggestions for fix it? (i use python 3.9)

def decrypt(string, shift):
    cipher = ''
    for char in string:
        if char == ' ':
            cipher = cipher + char
        elif char.isupper():
            cipher = cipher + chr((ord(char) - shift - 65) % 26 + 65)
        else:
            cipher = cipher + chr((ord(char) - shift - 97) % 26 + 97)

    return cipher


text = open(input("enter string: "))
s = int(input("enter shift number: "))
print("original string: ", text)
print("after decryption: ", decrypt(text, s))
cla
  • 13
  • 1

1 Answers1

3

text is an iterable that produces a sequence of strings, one per line from the file. As a result, char is an entire line of the file, not a single character of a given line.

decrypt is fine (though you should use the join method rather than repeatedly appending characters to a growing string); it's your use of text that needs to be fixed.

text = open(input("enter string: "))
s = int(input("enter shift number: "))
for line in text:
    print("original string: ", line)
    print("after decryption: ", decrypt(line, s))

If you want the entire file as a single string, call its read method directly:

text = open(input("enter string: ")).read()
s = int(input("enter shift number: "))
print("original string: ", text)
print("after decryption: ", decrypt(text, s))

(I'm deliberately ignoring any str-vs-bytes issues regarding the use of the data read from text.)

chepner
  • 497,756
  • 71
  • 530
  • 681