【发布时间】:2020-04-29 16:41:17
【问题描述】:
当我做这个输入时
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 行的字符串格式化期间并非所有参数都转换了 问题是什么,为什么以及如何解决它
【问题讨论】:
-
index是一个 字符串,所以%是 printf-style formatting not 模。请参阅规范的stackoverflow.com/q/20449427/3001761。另请注意,您不需要从长度中减去 1 以将索引环绕在列表的末尾,除非您实际上试图错过最后一个值。 -
看起来
index应该是int,而不是string。顺便说一句,以这种方式使用全局变量是非常糟糕的做法。您应该利用返回值、参数和 OOP。 -
@iz_ 打败了我!您的程序确实需要一些重构。此外,始终共享整个错误消息,并使用上下文管理器来处理该文件对象。