Hello I want to use the .startswith method, but I could only get it to work with one word.
I want more than one word.

For example what I did:

if text.startswith('welc')
   print('Welcome')

but I wanted:

list = ['welc', 'hey', 'sto']

if text.startswith(list)
   print('It works')
# This doesn't work
有帮助吗?

解决方案 2

You can use any():

>>> s = "welcome"
>>> l = ['welc', 'hey', 'sto']
>>> any(s.startswith(i) for i in l)
True

其他提示

As the documentation says, the argument must be a tuple. Oddly, lists do not work. So:

text = "welcome"
greets = ("welc", "hey", "sto")

if text.startswith(greets):
    print("Welcome")

The documentation for startswith() says that you can pass it a tuple of strings e.g.

list = ('welc', 'hey', 'sto')

and passing this to the startswith() leads to the output True. But it does not tell you which word it was that returned True. If you wan't to know that you can use a loop.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top