You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中endswith()如何匹配多个后缀值 解决传参报错问题

问题根因

Python字符串的endswith()方法支持匹配多个后缀,但要求多个后缀必须以元组形式传入。你当前写法直接传了三个独立字符串参数,后两个参数会被方法识别为切片起止位置参数,传入的字符串"!"、"?"不符合切片索引的类型要求,因此触发TypeError: slice indices must be integers or None or have an __index__ method报错。

整洁实现代码

不需要新增额外判断分支,只需要修正传参格式,同时抽离重复的拼接逻辑减少冗余即可:

import sys

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

内容的提问来源于stack exchange,提问作者slyrp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 03:15:47