1

I am using data scraped from a website and making my bot display in separate lines. There is a particular string whose information has "\n" in between and I want to convert those into actual line breaks

I have tried replacing the '\n' with '+ "\n" +' but the output is still the same

This is an example of the issue I have, and not the actual bot code

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)

I expected something like this:

Card Name

This is an ability

This is another ability

Instead what I get is:

Card Name

This is an ability\nThis is another ability

SaltyHelpVampire
  • 305
  • 2
  • 4
  • 15
  • surely instances of "\n" in a non-raw string literal are already linebreaks? Unless the rawCardText (use snake_case for python btw.) variable is being loaded from a source with literal "\" + "n", or in terms of python string literals, "\\n" or r"\n" – Sam Rockett Feb 09 '19 at 10:41
  • I am no python expert but apparently the "\n" strings that come with the text I scrape are raw and that is why they didn't work until I detected them as raw and replaced them by non-raw, as the answer I accepted suggested I did. The '+ "\n" +' is not needed and it was even a mistake, only "\n" is needed. _Edit:All of this refering to how Discord processes them on messages, I do not know if the same applies to a simple `print()` command because the other answer I didn't accept worked on python console but not on Discord_ – SaltyHelpVampire Feb 09 '19 at 11:39
  • Thats because the other answer assumed the text you wrote is the text you were getting. in python string literals, "\n" renders as a single newline character, that answer then used that single newline character to split on. Whereas what you actually wanted was a literal "\" and the letter "n", which in a python string literal is written as either "\\n" or r"\n". – Sam Rockett Feb 09 '19 at 11:52
  • Makes sense, maybe I could have stated what I wanted a bit more clearly. Regardless, I got my answer and now thanks to your help I know what the exact issue was – SaltyHelpVampire Feb 09 '19 at 11:57

2 Answers2

2
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

anand_v.singh
  • 2,768
  • 1
  • 16
  • 35
1

Write "\n" as raw string:

cardText = rawCardText.replace(r'\n', '+ "\n" +')
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39