考虑以下代码:
my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
我需要检查输入是否以集合中的任何一个字符串开头,如果是则执行一些代码。例如,如果输入是“apple is tasty”,那么它应该执行一些代码,否则就通过。我该怎么做?
最佳答案
您可以简单地使用:
my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
output = any(x.startswith(i) for i in my_items)
print(output)
输出:
Enter a string : apple is tasty
True
如果无论大小写你都希望它是真的,你可以使用:
my_items = {'apple','banana','orange'}
x = input("Enter a string : ")
output = any(x.lower().startswith(i.lower()) for i in my_items)
print(output)
关于python - 如何查找输入是否以集合中的某个字符串开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70958854/