Python 3: Write newlines to HTML
Asked Answered
C

7

7

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.

Cagle answered 21/11, 2009 at 17:11 Comment(2)
html entities 
 (carriage return) and 
 (line feed) don't failHaggerty
This does not work since these are "HTML entities", ASCII codes for rendered characters. So my source page ends up looking like this: New</a> &middot;&#32;&#13;<a href=?Cagle
C
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

Cagle answered 2/12, 2009 at 18:0 Comment(1)
If you mark this answer as correct, more people will see it! :)Brno
D
8

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

Decolorize answered 21/11, 2009 at 17:21 Comment(5)
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.Lorelle
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.Cagle
how about =s.replace("&#13;","\n") Gnarlodious?Decolorize
@Gnarlodious: The question "backslash escaped newlines". Does that mean "\\n"? A backslash character () and an n? If so, replace( "\\n", "<br />" ) would work.Resent
@Resent - 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').Jongjongleur
C
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

Cagle answered 2/12, 2009 at 18:0 Comment(1)
If you mark this answer as correct, more people will see it! :)Brno
E
0

Maybe I don't get it, but isn't <br /> some kind of newline for HTML?

s = "Hello HTML\n"
to_render = s.replace("\n", "<br />")

If you render something with mimetype "text/plain" \newlines should work.

Enjambement answered 21/11, 2009 at 17:16 Comment(1)
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?Cagle
H
0

If you are using Django, this answer will be helpful.

It's about how you render the page and whether you escape HTML or no.

Hawkes answered 13/12, 2017 at 14:37 Comment(0)
I
0

Since I have solved basic Markdown, I have resolved the new lines with a regular expression.

import re
br = re.compile(r"(\r\n|\r|\n)")  # Supports CRLF, LF, CR
content = br.sub(r"<br />\n", content)  # \n for JavaScript
Irrational answered 19/1, 2019 at 16:47 Comment(0)
W
0

For me, using Python 3.8.0, adding the string <br /> in the string I want displayed onto the html page, and then encoding the final string in utf-8 does the trick. Take a look at the following code:

min_value = 1
max_value = 10
output_string = "min =" + min_value
output_string += "<br /> max =" + max_value

return output_string.encode('utf-8')

For example, if this code is used as the implementation of a REST API endpoint, then calling this endpoint will display:

min =1
max =10

Waggish answered 26/3, 2024 at 14:16 Comment(0)
M
-1

Print() should add a newline by default - unless you tell it otherwise. However there have been other changes in Python 3:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

Old = Python 2.5, New = Python 3.

More details here: http://docs.python.org/3.1/whatsnew/3.0.html

Millur answered 21/11, 2009 at 17:22 Comment(1)
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.Cagle

© 2022 - 2025 — McMap. All rights reserved.