【发布时间】:2021-01-05 13:44:17
【问题描述】:
我想在 .txt 文件中搜索某个字符 (X),如果存在,请执行某个操作。不幸的是,这段代码不起作用:
file = "test.txt"
file = open(file, "r")
lines = file.readlines()
# char in the list
if "X" in lines:
print('X is present in the list')
# char not in the list
if "X" not in lines:
print('X is not present in the list')
test.txt 文件:
XX X XXX X XX
XXXXX XX X XX
有什么想法吗?
P.S.:即使将“X”更改为“X”也不起作用。
【问题讨论】:
-
if "X" not in Zeilen:中的变量Zeilen是什么? -
lines是一个字符串列表。没有一行与字符串"X"完全匹配。 -
How to debug small programs。逐步检查您的代码并查看
lines包含的内容。'X' in lines会是True吗?在 Python 中,"X"和'X'也意味着同样的事情。 -
将
"x" in lines替换为if any("X" in words for words in lines):。它将在列表中的字符串中查找 x -
Zeilen 只是翻译错误,抱歉。我刚刚用英语为你重命名了变量