[英]TypeError: string indices must be integers inpython
這是我的代碼:
import time
ed = input('Encrypt (e) or decrypt (d)? ')
chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
charsLen = len(chars)
def numberToStr(num):
s = ""
while num:
s = chars[num % charsLen] + s
num //= charsLen
return(s)
def strToNumber(numStr):
num = 0
for i, c in enumerate(reversed(numStr)):
num += chars.index(c) * (charsLen ** i)
return(num)
def enc():
key = input('What is your key? (Alphanumeric and space) ')
ID = int(input('What is your ID? (0-9, 3+ digits) '))
inp = int(strToNumber(input('What do you want to encrypt? ')))
keyAsNum = int(strToNumber(key))
enc.asint = inp ** 2
enc.asint = enc.asint * ID
enc.asint = enc.asint - keyAsNum
enc.astext = numberToStr(int(enc.asint))
return(enc)
def dec():
key = input('What is your key? (Alphanumeric and space) ')
ID = int(input('What is your ID? (0-9, 3+ digits) '))
inp = int(strToNumber(input('What do you want to decrypt? ')))
keyAsNum = int(strToNumber(key))
message = inp + keyAsNum
message = message // ID
message = math.sqrt(message)
message = numberToStr(message)
return(message)
if ed=='e':
crypt = enc()
print('crypt.asint:\n' + str(crypt.asint) + '\ncrypt.astext:\n' + crypt.astext)
elif ed=='d':
crypt = dec()
print(crypt)
time.sleep(10)
這是錯誤:文件“stdin”,第 5 行,在模塊中
文件“stdin”,第 9 行,在 dec
文件“stdin”,第 4 行,在 numberToStr 中
類型錯誤:字符串索引必須是整數
我不知道為什么它會拋出這個錯誤並且在谷歌上找不到任何東西。
回溯會准確地告訴您出了什么問題。 你在做
s = chars[num % charsLen] + s
但您不確定 num 是 int ,因為以前,您這樣做:
message = math.sqrt(message)
message = numberToStr(message)
math.sqrt
返回什么類型?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.