Question

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
Was it helpful?

Solution 2

You can use any():

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top