为什么我的 for 循环 运行 无限期并且在满足 if 条件时不停止?

Why does my for loop run indefinitely and doesn't stop when the if condition is met?

我正在尝试从文件中读取文本并使用循环从文件中查找特定文本。文件中的数据逐字垂直列出。 当我 运行 脚本时,在它打印文件中的最后一个单词后,它会无限期地从头开始重复。

with open('dictionary.txt','r') as file:
    dictionary = file.read().strip()
for i in dictionary:
 print (dictionary)
 if( i == "ffff" ):
    break

首先将行拆分为 "\n" 然后 print(i) 而不是 print(dictionary):

with open('dictionary.txt', 'r') as file:
    dictionary = file.read().strip().split("\n")
for i in dictionary:
    print(i)
    if i == "ffff":
        break

之前,你应该 split 行 b/c 它会循环到字符串中并检查字符是否是 ffff,它不会是 True

我是一个角色,你先做

dictionary = dictionary.split("\n")

BUT 如果你的 ffff 是一行,如果是用空格分隔的单词你可以这样做:

dictionary = dictionary.split(" ")