如何用换行符替换字符串中“\n”的所有实例

2024-10-02 00:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的数据从网站上刮下来,使我的机器人显示在单独的行。有一个特殊的字符串,它的信息中间有“\n”,我想把它们转换成实际的换行符

我已尝试用“+”\n“+”替换“\n”,但输出仍然相同

这是我遇到的问题的一个例子,而不是实际的bot代码

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio

Client = discord.Client()
client = commands.Bot(command_prefix = "!")

cardName = "Card Name"
rawCardText = "This is an ability\nThis is another ability"
cardText = rawCardText.replace('\n', '+ "\n" +')

fullText = cardName + "\n" + cardText
await client.send_message (message.channel, fullText)

我以为会是这样的:

卡片名称

这是一种能力

这是另一种能力

相反,我得到的是:

卡片名称

这是一种能力\n这是另一种能力


Tags: fromimportclientisbot能力extcommands
2条回答

"\n"写入raw string

cardText = rawCardText.replace(r'\n', '+ "\n" +')
cardName = "Card Name"
rawCardText = "This is an ability\nThis is another ability"
cardText = rawCardText.split('\n')
fullText = fullText = (cardName + '\n' + '\n'.join(cardText))
print (fullText)

enter image description here

相关问题 更多 >

    热门问题