Frederik
Frederik

Reputation: 409

text.startswith method with multi words

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

Upvotes: 1

Views: 574

Answers (3)

Thrasi
Thrasi

Reputation: 498

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.

Upvotes: 1

kindall
kindall

Reputation: 184211

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")

Upvotes: 2

alecxe
alecxe

Reputation: 473873

You can use any():

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

Upvotes: 1

Related Questions