0

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.

slyrp
  • 1

1 Answers1

0

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 [".", "!", "?"]:
seermer
  • 571
  • 6
  • 12
  • Wow! That helped a ton. I did find out the first method but I will use the second method because of what you said. Thank you so much! – slyrp Jul 02 '22 at 06:58