Python 2:一行或非常紧凑的代码,用于检查几个字符串的"startswith"?

fdm*_*ion 0 python list

场景:

我有一个清单:

['item','place','thing']
Run Code Online (Sandbox Code Playgroud)

我有一些字符串:

"item", "item1", "thing55", "place_C", "stuff", "junk5"
Run Code Online (Sandbox Code Playgroud)

在上面,我希望前四个匹配,最后两个不匹配.startswith函数最适合此检查.

(测试字符串"item","item1"等的列表不是python列表;它只是一组可能被检查的样本数据.但是,要匹配"item","place"的字符串列表,"thing"是代码中的python列表.)

我可以遍历第一个列表并将字符串与startswith进行比较:

successVar = False
for s in myStrings:
    if (testString.startswith(s)): 
        successVar = True
        break
#  Now you would check successVar to decide if string matched
Run Code Online (Sandbox Code Playgroud)

但在所有情况下,这并不一定最好.例如,假设这是if/elif结构的一部分:

if (testString == "hello"):
    # do something based on exact string match
elif (testString.endswith("!")):
    # do something if string ends with _one_ specific entity
elif <somehow, do the above comparison in here>
    # do something if string starts with any of the items in a list
else:
    # do something if string didn't match anything
Run Code Online (Sandbox Code Playgroud)

我想我可以将整个检查包装在一个函数中,但我觉得可能有一种方法可以更容易或更简洁地使用内联代码.

这甚至可以在没有功能的情况下完成吗?

谢谢

Sve*_*ach 10

str.startswith() 接受一组前缀:

>>> "item1".startswith(("item","place","thing"))
True
Run Code Online (Sandbox Code Playgroud)

  • @SrinivasReddyThatiparthy:我认为它只是元组,而不是任意的迭代,以避免必须检查C代码中的递归. (2认同)