Python 3: Write newlines to HTML

24,236

Solution 1

The solution is:

#!/usr/bin/python 
 import sys 
 def print(s): return sys.stdout.buffer.write(s.encode('utf-8'))
 print("Content-type:text/plain;charset=utf-8\n\n") 
 print('晉\n') 

See the original discussion here: http://groups.google.com/group/comp.lang.python/msg/f8bba45e55fe605c

Solution 2

normally I do like this s=s.replace("\n","<br />\n")

because

<br /> is needed in web page display and

\n is needed in source display.

just my 2 cents

Share:
24,236
Gnarlodious
Author by

Gnarlodious

Python, SQLite, linguistics

Updated on July 09, 2022

Comments

  • Gnarlodious
    Gnarlodious almost 2 years

    I have upgraded to Python 3 and can't figure out how to convert backslash escaped newlines to HTML.

    The browser renders the backslashes literally, so "\n" has no effect on the HTML source. As a result, my source page is all in one long line and impossible to diagnose.

  • Brian R. Bondy
    Brian R. Bondy over 14 years
    I would suggest to first replace \r\n with \n and then \n with <br/> so you don't end up with some \r in your string.
  • Gnarlodious
    Gnarlodious over 14 years
    This does not work since my output does not already have newlines in it. In any case, apparently Python 3 does not convert UNIX style escaped characters into the appropriate ASCII characters.
  • Gnarlodious
    Gnarlodious over 14 years
    This does not work since I am assembling strings and returning the result. If I were printing directly from the script it might be OK.
  • Gnarlodious
    Gnarlodious over 14 years
    Yes, in fact newlines ARE working! It seems that I am saying<br> <pre>print("Content-type:text/html\n\n", HTML.encode("utf-8"))</pre><br>so the conversion to UTF8 is wiping out my newlines! And actually, Python 3 is all about UTF8, so that conversion is unnecessary. However, removing the conversion gives me error:<br> <pre> UnicodeEncodeError: 'ascii' codec can't encode character '\u8e47' in position 14525: ordinal not in range(128)<pre><br>So what is happening? Can anyone tell me how to format text on this site?
  • YOU
    YOU over 14 years
    how about =s.replace("&#13;","\n") Gnarlodious?
  • user1066101
    user1066101 over 14 years
    @Gnarlodious: The question "backslash escaped newlines". Does that mean "\\n"? A backslash character () and an n? If so, replace( "\\n", "<br />" ) would work.
  • PaulMcG
    PaulMcG over 14 years
    @S.Lott - G'odious is saying that his HTML source has no newlines in it, so the substitution string should put in a newline too. In fact, it's not clear that he/she want the HTML <BR>s in there, just not all the HTML on one line. I think the desired code is s = s.replace(r'\n','\n').
  • Chris Cooper
    Chris Cooper over 10 years
    If you mark this answer as correct, more people will see it! :)