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

如何在Discord.py命令中自动将单引号'转义为URL编码%27?

方案1:使用Python标准库做URL编码(推荐)

该方法可一次性处理所有URL非法字符,不止能转义单引号为%27,空格、特殊符号、中文等场景也能自动适配,避免后续其他词条出现类似失效问题。

  1. 先在代码头部导入所需模块:
from urllib.parse import quote
# 保留你原有其他导入代码
  1. 修改命令逻辑如下:
@client.command()
async def mlwiki(ctx, *args):
    # 拼接词条并完成首字母大写处理
    search_term = '_'.join([arg.capitalize() for arg in args])
    # 完成URL编码,自动替换单引号等特殊字符
    encoded_term = quote(search_term)
    embed = discord.Embed(
        title="你的Wiki搜索结果:", 
        description=f'**[结果链接](https://monsterlegends.fandom.com/wiki/{encoded_term})**', 
        color=0x00ff00
    )
    embed.set_footer(text ="注意:如果输入的词条名称有误,链接将无法正常访问")
    await ctx.reply(embed=embed, mention_author=False)

方案2:仅替换单引号

如果你确认只需处理单引号问题,不需要适配其他特殊字符,也可以直接用字符串替换方法,无需额外导入模块:

@client.command()
async def mlwiki(ctx, *args):
    search_term = '_'.join([arg.capitalize() for arg in args]).replace("'", "%27")
    embed = discord.Embed(
        title="你的Wiki搜索结果:", 
        description=f'**[结果链接](https://monsterlegends.fandom.com/wiki/{search_term})**', 
        color=0x00ff00
    )
    embed.set_footer(text ="注意:如果输入的词条名称有误,链接将无法正常访问")
    await ctx.reply(embed=embed, mention_author=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 20:45:04