1

I am trying to write (excel file) /print a dataframe , where column values consists of next line (\n) .

>>> textbox = ""
>>> textbox+=str('So, so you think you can tell \n')
>>> textbox+=str('Heaven from hell')
>>> print textbox
So, so you think you can tell 
Heaven from hell
>>> df1 = pd.DataFrame({'lyric':[textbox]})
>>> df1
                                              lyric
0  So, so you think you can tell \nHeaven from hell
>>> print df1
                                              lyric
0  So, so you think you can tell \nHeaven from hell

So when i print the df or write a to excel file , I see that instead of next line , "\n" is printed.

How to print next line?

Bharat Sharma
  • 1,081
  • 3
  • 11
  • 23

1 Answers1

0

I think you need create lists from string by split with \n, then strip start and end whitespaces:

splitlines solution:

df1 = pd.DataFrame({'lyric':textbox.splitlines()})
df1.lyric = df1.lyric.str.strip()
print (df1)
                           lyric
0  So, so you think you can tell
1               Heaven from hell

split solution:

print (textbox.split('\n'))
['So, so you think you can tell ', 'Heaven from hell']

df1 = pd.DataFrame({'lyric':textbox.split('\n')})
df1.lyric = df1.lyric.str.strip()
print (df1)
                           lyric
0  So, so you think you can tell
1               Heaven from hell

strip by list comprehension:

df1 = pd.DataFrame({'lyric':[x.strip() for x in textbox.split('\n')]})
print (df1)
                           lyric
0  So, so you think you can tell
1               Heaven from hell

EDIT:

I think you need replace:

df1 = pd.DataFrame({'lyric':[textbox]})
df1.lyric = df1.lyric.str.replace('\n', '')
print (df1)
                                            lyric
0  So, so you think you can tell Heaven from hell
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks . what I need to do if I have to print both lines under same index = 0. Will both line be printed in same cell if I use df1.to_excel() – Bharat Sharma Mar 27 '17 at 09:56
  • Not possible to print two lines one after another instead of printing them in one line. I am trying to insert line break between many lines of an 'excel cell value' . – Bharat Sharma Mar 27 '17 at 10:49
  • Do you need [this](http://stackoverflow.com/a/18822775/2901002) ? only change `sheet.write(0, 1, 'Hello\nWorld', style)` to `sheet.write(0, 1, df1['lyric'].iloc[0], style)` – jezrael Mar 27 '17 at 11:24
  • and another solutions [here](http://stackoverflow.com/a/15384171/2901002) – jezrael Mar 27 '17 at 11:25
  • I am printing large data frame for that I am using writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') – Bharat Sharma Mar 27 '17 at 17:21