问题
My function is supposed to take a string argument as input, and return the rot-13 encoding of the input string.
def str_rot_13(string):
c = list(string)
for num in c:
if ord(num) >= ord('a') and ord('z'):
if ord(num) >=('m'):
ord(num) -=13
else:
ord(num) +=13
elif ord(num) >= ord('A') and ord('Z'):
if ord(num) >=('M'):
ord(num) -=13
else:
ord(num) +=13
z += chr(ord(num))
return z
It's giving me a "can't assign to function call" error. I'm not sure what I'm doing wrong.
Edit: Finally got it to work! Thanks.
The solution:
if ord(num) >= ord('a') and ord('z'):
if ord(num) >=('m'):
k+= chr(ord(num)-13)
else:
k+= chr(ord(num)+13)
elif ord(num) >= ord('A') and ord('Z'):
if ord(num) >=('M'):
k+= chr(ord(num)-13)
else:
k+= chr(ord(num)+13)
return k
回答1:
What you're doing wrong is, you're assigning to a function call! E.g:
ord(num) -=13
you're assigning to the function call ord(num) -- and, you can't do it.
What you actually want to do is presumably:
num = chr(ord(num) - 13)
and so on.
Of course, you'll still have problems appending to z unless you define z in a part of the code you chose not to show us. Hard to help debug code you choose to hide from us, of course.
回答2:
The problem is with lines like this one:
ord(num) -=13
ord is a built-in function. You can use a value returned by a function, but not assign a value to a function.
What you can do instead is:
num = chr(ord(num) - 13)
This will probably not solve your problem, as you have other bugs, like you are trying to add to variable z without declaring it somewhere. You should declare it before your for loop:
z = ''
for num in c:
...
and also indent the line
z += chr(ord(num))
so that it is inside the for loop. You can also make it:
z += num
as chr and ord are reverse functions.
来源:https://stackoverflow.com/questions/28652444/cant-assign-to-function-call-error