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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12783705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:52:06  来源:igfitidea点击:

If any item of list starts with string?

pythonliststartswith

提问by tkbx

I'm trying to check is any item of a list starts with a certain string. How could I do this with a for loop? IE:

我试图检查列表中的任何项目是否以某个字符串开头。我怎么能用 for 循环做到这一点?IE:

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

采纳答案by Ashwini Chaudhary

Use any():

使用any()

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

回答by SeanJohn

If you want to do it with a for loop

如果你想用 for 循环来做

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

the 0:5 takes the first 6 characters in the string you can adjust it as needed

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