python - 如何查找输入是否以集合中的某个字符串开头

标签 python

考虑以下代码:

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/

相关文章:

Python不打印所有sys.argv

python - Pandas:str 类型的列在使用 apply 函数后转换为 tslib.Timestamp

python - 在 python 中解析以分号分隔的文件以创建 CSV

python - 如何让我的 Discord 机器人删除 channel 中的所有消息?

python - 类型错误 : cannot concatenate 'str' and 'UUID' objects

python - 在View中访问Django Form报错信息

python - 在Python中有效比较两列中的每对日期

Python 简单套接字 - 从客户端请求获取 URL

python - 在列表中查找数字递增(具有不同增量)的组

python - 最大()函数 : how to get the item being iterated and pass to key=func()