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

Discord.py报错TypeError:列表索引需为整数/切片而非字符串

解决Discord.py队列功能中的TypeError问题

嘿,这个错误很常见,我来帮你理清问题所在并修复它!

错误原因分析

你遇到的TypeError: list indices must be integers or slices, not str,核心问题出在这段循环代码里:

for str in song_names:
    await ctx.channel.send(counter + song_names[str])

这里的str是song_names列表中的元素本身(比如'Masked Wolf - Astronaut in the Ocean'这类字符串),但你却把它当成列表的索引去调用song_names[str]——而列表的索引只能是整数或切片,不能是字符串,所以触发了类型错误。另外还有个隐藏问题:counter是整数,直接和字符串拼接也会报错,得先把它转成字符串类型。

修复后的代码方案

推荐用enumerate()函数来同时获取起始计数和歌曲元素,这样代码更简洁易读,还能避免手动维护计数器的麻烦:

song_names = ['Masked Wolf - Astronaut in the Ocean', 'Billie Eilish - bad guy']

async def queue(ctx):
    # enumerate的第二个参数指定计数从1开始
    for counter, song in enumerate(song_names, 1):
        # 用f-string优雅拼接计数和歌曲名
        await ctx.channel.send(f"{counter}. {song}")

如果你更倾向于手动维护计数器的写法,也可以改成这样:

song_names = ['Masked Wolf - Astronaut in the Ocean', 'Billie Eilish - bad guy']

async def queue(ctx):
    counter = 1
    print(song_names)
    # 直接遍历列表中的每个歌曲元素
    for song in song_names:
        await ctx.channel.send(f"{counter}. {song}")
        counter += 1

额外小贴士

  • 尽量不要用str作为变量名,因为str是Python的内置类型名称,这样做会覆盖内置功能,容易引发其他潜在问题,换成song这种有意义的名字更合适。
  • 使用f-string(f"{counter}. {song}")来拼接字符串是Python 3.6+的推荐写法,比str(counter) + ". " + song更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:30:01