You need to enable JavaScript to run this app. Python运行报错AttributeError: 'NoneType'对象无endswith属性求助
优惠活动
大模型
产品
解决方案
定价
更多

Python运行报错AttributeError: 'NoneType'对象无endswith属性求助

报错原因

  • 问题出在代码行 Prep = print(re.sub(r" ?\([^)]+\)", "", result))
  • Python 中 print() 函数的作用是向控制台输出内容,本身的返回值为 None。你将 print() 的返回值赋值给了 Prep 变量,后续对 Prep 调用字符串方法 endswith() 本质就是对 None 调用不存在的属性,所以触发对应的属性错误。
  • 补充:原代码中给 Caption 赋值时也直接取了 print() 的返回值,如果后续需要使用 Caption 变量,同样会得到 None,也需要同步修正。

修正后代码

import re
result = "hey(14).jpg"

# 先完成正则替换,将结果赋值给Prep
Prep = re.sub(r" ?\([^)]+\)", "", result)
# 单独打印替换后的结果
print(Prep)

if Prep.endswith('jpg'):
    Caption = Prep.replace("jpg", "is jpg")
elif Prep.endswith('png'):
    Caption = Prep.replace("png", "is png")
elif Prep.endswith('gif'):
    Caption = Prep.replace("gif", "is gif")
else:
    Caption = "Unknown"

# 打印最终结果
print(Caption)

运行修正后代码会输出:

hey.jpg
hey.is jpg

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 15:45:05