Frage

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
War es hilfreich?

Lösung 2

You can use any():

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

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top