为什么说Typ​​eError:不是在格式化字符串时转换了所有参数?

输入时

def enter_file():
        global file
        file = open(r"c:\words.txt","w")
        file.write("dog bee bear cat")
        file.close()
        global file_path
        file_path = input("please enter a file path: ")
        global index
        index = input("please enter an index: ")

def choose_word(file_path,index):
        file = open(file_path,"r")
        words_list = file.read().split(" ")
        no_doubles = list(dict.fromkeys(words_list))
        tuple_out = []
        tuple_out.append(len(no_doubles))
        tuple_out.append(words_list[index % len(words_list) - 1]) 
        global secret_word
        secret_word = tuple_out[1]   
        print("_ " * len(secret_word)) 

def main():
        print(enter_file())
        print(choose_word(file_path,index))

if __name__ == '__main__':
        main() 

我收到类型错误回溯,内容为: TypeError:在第17行的字符串格式化期间,并非所有参数都已转换 有什么问题,为什么以及如何解决

budianxyl 回答:为什么说Typ​​eError:不是在格式化字符串时转换了所有参数?

我建议您将索引输入转换为int变量,以确保可以从单词列表中选择一个整数索引。

def enter_file():
        global file
        file = open(r"c:\words.txt","w")
        file.write("dog bee bear cat")
        file.close()
        global file_path
        file_path = input("please enter a file path: ")
        global index
        index = input("please enter an index: ")

def choose_word(file_path,index):
        file = open(file_path,"r")
        words_list = file.read().split(" ")
        no_doubles = list(dict.fromkeys(words_list))
        tuple_out = []
        tuple_out.append(len(no_doubles))
        tuple_out.append(words_list[int(index) % len(words_list) - 1]) 
        global secret_word
        secret_word = tuple_out[1]   
        print("_ " * len(secret_word)) 

def main():
        print(enter_file())
        print(choose_word(file_path,index))

if __name__ == '__main__':
        main()
本文链接:https://www.f2er.com/2780955.html

大家都在问