How to search multiple values in endswith Python?

257 Views Asked by At

Currently I'm making a bot with OpenAI GPT-3. I'm trying to see if the responses end with ".", "!", or "?" to stop generating responses. Here's my code:

if a4.endswith(".", "!", "?"):
  if int(len(a + a2 + a3 + a4)) < 50:
    tc3 = a + a2 + a3 + a4
    print(tc3)
    raise sys.exit()
  else:
    tc3 = a + a2 + a3 + a4 + "."
    print(tc3)
    raise sys.exit()

This doesn't work and returns the error

TypeError: slice indices must be integers or None or have an index method

I'm wondering I could do without making more if statements because I want my code to look as least messy as possible so I can read the code.

1

There are 1 best solutions below

1
seermer On

I think it is impossible to use a single endswith.
If you have to use endswith, one way is to use multiple endswith:

if a4.endswith(".") or a4.endswith("!") or a4.endswith("?"):

However, I personally suggest using index and in instead:

if a4[-1] in ".!?":

which I think is more pythonic and readable.

What this does is first find the last character of string with index -1, then check if this character is in the matching string ".!?"

alternatively, you can put the matching strings in a list (or in fact any iterable).

if a4[-1] in [".", "!", "?"]: