如果列表中的任何项以字符串开头?

2024-05-15 09:07:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在检查列表中是否有以特定字符串开头的项。我怎么能用for循环呢?即:

anyStartsWith = False
for item in myList:
    if item.startsWith('qwerty'):
        anyStartsWith = True

Tags: 字符串infalsetrue列表forifitem
2条回答

使用^{}

any(item.startswith('qwerty') for item in myList)

如果你想用for循环

anyStartsWith = False
for item in myList:
    if item[0:5]=='qwerty':
        anyStartsWith = True

0:5接受字符串中的前6个字符,您可以根据需要对其进行调整

相关问题 更多 >