문제

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