Discord机器人发送多行字符串消息出现布局错误 后续行带前置空格
问题原因
你使用的Python三引号多行字符串会严格保留代码编写时的缩进格式,你定义welcome_message时除了首行之外的内容在代码里都带了前置缩进,这些缩进会直接被存入字符串。你之前调用的lstrip()仅能移除整个字符串开头位置的空白字符,无法处理后续每行开头的多余缩进,因此问题没有解决。
修复方案
下面给出几种常用的修复方式,按需选择即可:
方案1:使用textwrap.dedent自动移除统一缩进(推荐)
这是Python官方提供的专门处理多行字符串多余公共缩进的工具,不会影响你原本的代码排版:
# 顶部先导入模块 import textwrap from discord.ext import commands client = commands.Bot(command_prefix = '/') @client.command() async def start(ctx): welcome_message = textwrap.dedent(""" Welcome to my bot here is a new line which has leading spaces this line here has some aswell """).strip() # 额外加strip()去掉首尾多余的换行 await ctx.send(welcome_message)
方案2:直接顶格写多行字符串
不需要额外导入模块,只需要调整三引号内内容的排版即可,缺点是代码缩进看起来不统一:
@client.command() async def start(ctx): welcome_message = f"""Welcome to my bot here is a new line which has leading spaces this line here has some aswell """ await ctx.send(welcome_message)
方案3:手动处理每行的缩进
如果你不想改现有字符串的写法,也可以自行切割处理每行的空白:
@client.command() async def start(ctx): welcome_message = f""" Welcome to my bot here is a new line which has leading spaces this line here has some aswell """ # 按行拆分,去掉每行前后空白后再用换行拼接 welcome_message = '\n'.join(line.strip() for line in welcome_message.splitlines() if line.strip()) await ctx.send(welcome_message)
内容的提问来源于stack exchange,提问作者CodeIsLaw
相关产品推荐
相关产品推荐

