首页 > 解决方案 > 使用不和谐机器人将多行字符串作为消息发送时出现布局错误

问题描述

我启动并运行了一个不和谐的机器人。我的目标是在某个命令后向用户发送消息。这行得通,但不知何故我的布局是错误的。我的字符串的第一行是正确的,然后其余的以一些前导空格发送。

client = commands.Bot(command_prefix = '/')

@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)

所以基本上我的信息是这样的:

Welcome to my bot
    here is a new line which has leading spaces
    this line here has some aswell

即使welcome_message = welcome_message.lstrip()在发送之前也无法修复它。

标签: pythonlayoutdiscord.pymultilinemultilinestring

解决方案


在这种情况下,缩进是字符串的一部分(因为它是多行字符串),您可以简单地将其删除:

@client.command()
async def start(ctx):
    welcome_message = 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)

如果要保留缩进,请使用以下textwrap.dedent方法:

import textwrap

@client.command()
async def start(ctx):
    welcome_message = 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(textwrap.dedent(welcome_message))

推荐阅读