I am trying to write a vigenere cipher encrypter in python. I am getting another error...
def vigenere(string,key):
for i in range(len(key)):
if key[i].isupper():
tempList = list(key)
tempList[i] = chr(ord(key[i])-65)
key = "".join(tempList)
elif key[i].islower():
tempList = list(key)
tempList[i] = chr(ord(key[i])-97)
key = "".join(tempList)
k = 0
newstring = ''
for i in string:
if i.isupper():
newstring = newstring + ((ord(i)-65)+(key[k % len(key)]))%26 + 65
elif i.islower():
newstring = newstring + ((ord(i)-97)+(key[k % len(key)]))%26 + 97
k = k + 1
return newstring
"unsupported operand type(s) for +: 'int' and 'str'" -- any help?
First, you need to change:
key[i] + ord(key[i])-97
To:
key[i] = ord(key[i])-97
It seems that is a mistyping.
Second, the ord(...)
function returns an int. You want to convert it back to a char using chr(...)
:
key[i] = chr(ord(key[i])-97)
Finally, in Python, strings are immutable. This means you can't change the individual char of a string. This is an easy way to do it:
if key[i].isupper():
tempList = list(key)
tempList[i] = chr(ord(key[i])-65)
key = "".join(tempList)
elif key[i].islower():
tempList = list(key)
tempList[i] = chr(ord(key[i])-97)
key = "".join(tempList)