Gnarlodious
Gnarlodious

Reputation: 324

Python 3: Write newlines to HTML

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.

Upvotes: 8

Views: 34067

Answers (7)

zerzevul
zerzevul

Reputation: 429

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

Upvotes: 0

Geekmoss
Geekmoss

Reputation: 682

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

Upvotes: 0

gevra
gevra

Reputation: 756

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.

Upvotes: 0

Gnarlodious
Gnarlodious

Reputation: 324

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

Upvotes: 1

Martin
Martin

Reputation: 40365

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

Upvotes: -1

YOU
YOU

Reputation: 123881

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

Upvotes: 8

miku
miku

Reputation: 188114

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.

Upvotes: 0

Related Questions