【问题标题】:Why does it says TypeError: not all arguments converted during string formatting?为什么它说 TypeError: not all arguments 在字符串格式化期间转换?
【发布时间】: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_ 打败了我!您的程序确实需要一些重构。此外,始终共享整个错误消息,并使用上下文管理器来处理该文件对象。

标签: python typeerror


【解决方案1】:

我建议您将索引输入转换为 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2018-05-17
    • 2021-08-19
    • 2012-06-22
    • 1970-01-01
    • 2022-06-12
    • 2020-08-23
    相关资源
    最近更新 更多