Telegram Bot displaying literal \n characters instead of line breaks when sending pandas DataFrame text

I’m working on a Telegram bot using the python-telegram-bot library and I’m having trouble with formatting when I send text from a pandas DataFrame.

Here’s my setup:

import pandas as pd
data = pd.read_csv('messages.csv')

My CSV file looks like this:

id content
01 hello \n world \n test
02 first \n second
03 line1 \n line2

When I search through the data based on user input:

result = data['content'].str.contains(update.message.text, case=False)

And send the response:

await update.message.reply_text(result)

The bot shows the literal “\n” characters instead of actual line breaks. So instead of:

hello
world
test

I get:

hello \n world \n test

I tried changing the column data type and different CSV encodings but nothing worked. Any ideas how to fix this formatting issue?

This happens because pandas reads \n as literal text instead of actual line breaks. I ran into the same thing building a notification bot that pulled templates from a database. Use Python’s codecs module to fix it: import codecs then decoded_text = codecs.decode(your_text, 'unicode_escape'). This works for newlines, tabs, quotes - basically any escape sequence in your CSV. Just decode the text before sending it through Telegram’s API and you’re good to go.

I encountered a similar issue when using python-telegram-bot with pandas. The newline characters in the DataFrame appear as literal \n, causing formatting problems. To resolve this, you can apply the replace method to the content right after retrieving it from the DataFrame. For example, after filtering your data, use the following: formatted_message = filtered_data.replace('\\n', '\n'). This adjustment will ensure the text is formatted correctly when sent through the bot.

same thng happened to me too! just use .replace() on ur text b4 sending it: msg_text = your_dataframe_value.replace('\\n', '\n') otherwise pandas will treat \n as text, convert it to real line breaks!