5

I've tried using the or function to input multiple words for the same output, but it only takes the first word as the input and not the rest. How do I solve this? Thanks! For instance:

message.content.startswith("hi" or "hey")

only takes in "hi" as an input and not "hey".

I've tried adding the words in to a list and it doesn't work as well. I'm relatively new to coding so i'm sorry in advance if it's a stupid question

Maicon Mauricio
  • 2,052
  • 1
  • 13
  • 29
user268493
  • 65
  • 1
  • 4
  • `startswith` is likely just the standard built-in string method. And `startswith("hi" or "hey")` is equivalent to `startswith("hi")`. You'd need to manually check both by doing something like calling `startswith` twice. – Carcigenicate May 28 '21 at 15:57
  • Ahh, I was afraid that was the case. Now I have to manually input all the functions. Thanks! – user268493 May 28 '21 at 15:58
  • I'm not sure what you mean by "Now I have to manually input all the functions.". You can just do `msg = message.content; msg.startswith("hi") or msg.startswith("hey")`. I introduced `msg` for the sake of brevity. – Carcigenicate May 28 '21 at 16:00
  • 1
    You can use the builtin [`any`](https://docs.python.org/3/library/functions.html#any) here: `any(message.content.startswith(s) for s in ["hi", "hey"])` – Alex May 28 '21 at 16:00
  • @Alex why not turn that into an answer. – Buddy Bob May 28 '21 at 16:02
  • The `or` is not a function. It's an operator which returns the first truthy value according to what Python considers true. `"hi"` is always true, and that's why it is always returned. If you used `"" or "hey"`, for example, it would've returned hey. See [this](https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false#39984051) – Maicon Mauricio May 28 '21 at 16:14
  • It's worth taking a look at [this question](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-single-value) t learn a bit more about testing multiple values against a single variable. – Alex May 28 '21 at 16:17
  • 1
    Does this answer your question? [str.startswith with a list of strings to test for](https://stackoverflow.com/questions/20461847/str-startswith-with-a-list-of-strings-to-test-for) – Maicon Mauricio May 28 '21 at 17:24

1 Answers1

12

You can code like this:

message.content.startswith(("hi", "hey"))

From the Python documentation for str.startswith(prefix[, start[, end]]), I've added emphasis:

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

Alex
  • 6,610
  • 3
  • 20
  • 38
Danilo Toro
  • 569
  • 2
  • 15