我想查找列表元素中是否包含特定字符串。如果找到字符串,我想打印出“String found”,否则“String not found”。 但是,我想出的代码会多次打印“未找到字符串”。我知道原因,但我不知道如何修复它并只打印其中一条消息。
animals=["dog.mouse.cow","horse.tiger.monkey",
"badger.lion.chimp","trok.cat. bee"]
for i in animals :
if "cat" in i:
print("String found")
else:
print("String not found")
~
最佳答案
找到字符串时在if
block 中添加break
语句,将else
移动到else
for 循环。如果在这种情况下找到字符串,循环将中断,永远不会到达 else,如果循环不中断,将到达 else 并打印 'String not found'
。
for i in animals:
if 'cat' in i:
print('String found')
break
else:
print('String not found')
关于python - 从 for 循环中仅打印一次消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18763905/