0
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 Cipher matching algorithm, but I have a problem with the painting ord
, which tells me that I am providing a 2-character string instead of a character, but in reality it is not. I am 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 instruction, because if I modify it to:
if c >= 'A' and c <= 'z':
the program is executed.
c
in the loop is a character, and A
or z
are also, that’s why I don’t 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))
I cannot reproduce this error: In [5]:
message = "whatever"

In [6]: for c in message:
 ...: if ord('A') <= ord(c) <= ord('z'):
 ...: print("yes")
 ...:
– Lucas Virgili
Again no mistake, both with python 2.7 and 3. The only thing I changed was the condition for:
if ord('A') <= ord(c) <= ord('Z') and ord('a') <= ord(c) <= ord('z'):
since the letas are not contained in the ascii table.– Lucas Virgili
very strange indeed, here rotates normally :(
– Lucas Virgili
Let’s go continue this discussão in chat.
– Lucas Virgili
Have you tried printing
c
and see what comes? By the way, what operating system are you running on? And what encoding from your source file? (rather unlikely - in particular in Python 3 - but it may be that what appears to be 1 character for you internally is 2, by difference of encodings)– mgibsonbr
In fact it is difficult to reproduce the problem... Windows ran normally, and ideone (which I assume is Linux) also.
– mgibsonbr