if ord(c) >= ord('A') and ord(c) <= ord('z'):
TypeError: ord() expected a character, but string of length 2 found
I'm trying to create a casear cipher algorithm, but I have a problem with the ord
string, which tells me that I'm bundling a 2-character string instead of a character, but that's not really the case. I'm using the following loop to iterate through the string message
:
for c in message:
if ord(c) >= ord('A') and ord(c) <= ord('z'):
I know the error is in this statement, because if I modify it to:
if c >= 'A' and c <= 'z':
The program runs.
c
in the loop is a character, and A
or z
are too, that's why I do not understand where the problem is.
This is the full function code:
def encrypt(message, i=0):
emsg = ""
for c in message:
# to be decrypted, the character has to be in the range ["A", "z"]
if ord(c) >= ord('A') and ord(c) <= ord('z'): #
# Managing the case between upper and lower cases.
# Either if 'i' is negative or positive,
# the current letter is always replaced with
# a letter which can be found after it,
# in the ASCII encoding (in my case).
if ord(c) + i > 90 and ord(c) + i < 97: # [91, 96]
dif = (ord(c) + i) - 90 # positions remaining
emsg += chr(97 + dif - 1)
print("First if")
elif ord(c) + i > ord('z'): # ]122, - ]
dif = (ord(c) + i) - ord('z') # positions remaining
emsg += chr(ord('A') + dif - 1) # adds difference starting from 65
print("first elif")
elif ord(c) + i < ord('A'): # [ - , 65[
dif = ord('A') - (ord(c) + i) # positions remaining
emsg += chr(ord('z') - dif - 1)
print("second elif")
else: # simple case where we just advance the letter
emsg += chr(ord(c) + i)
print("else")
else: # It's not a normal char.
emsg += c
print("not a normal char.")
return emsg
print(encrypt(',bc', 1))