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

Python处理字符串列表移除下划线后内容报AttributeError如何解决

报错问题解决:删除字符串下划线后内容时出现AttributeError: 'NoneType' object has no attribute 'append'

错误原因

Python的列表append()方法是原地修改操作,执行后仅修改列表本身,返回值为None。你的代码中把clean_coins.append(test)的返回值重新赋值给了clean_coins变量,第一次循环结束后clean_coins就变成了None,第二次循环尝试对None调用append方法就会触发该报错。

修正方案

方案1:调整原有循环写法

删掉clean_coins = clean_coins.append(test)里的赋值操作,直接调用append方法即可:

import requests
url = 'https://data.gateapi.io/api2/1/pairs'
r = requests.get(url = url)
coins = r.json()

clean_coins = []
for coin in coins:
    test = coin.split("_")[0]
    clean_coins.append(test)

方案2:使用列表推导式简化代码

如果追求更简洁的写法,可以用列表推导式实现相同效果,代码更短执行效率也更高:

import requests
url = 'https://data.gateapi.io/api2/1/pairs'
r = requests.get(url = url)
coins = r.json()

clean_coins = [coin.split("_")[0] for coin in coins]

执行后clean_coins就是所有下划线前的字符串组成的列表。

内容的提问来源于stack exchange,提问作者Gloria Dalla Costa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:06:03