Python 3:将换行符写入 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1776066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3: Write newlines to HTML
提问by Gnarlodious
I have upgraded to Python 3 and can't figure out how to convert backslash escaped newlines to HTML.
我已升级到 Python 3,但不知道如何将反斜杠转义换行符转换为 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.
浏览器按字面呈现反斜杠,因此“\n”对 HTML 源代码没有影响。结果,我的源页面全部排成一行,无法诊断。
采纳答案by Gnarlodious
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
请参阅此处的原始讨论:http: //groups.google.com/group/comp.lang.python/msg/f8bba45e55fe605c
回答by YOU
normally I do like this s=s.replace("\n","<br />\n")
通常我喜欢这个 s=s.replace("\n","<br />\n")
because
因为
<br />
is needed in web page display and
<br />
在网页显示和
\n
is needed in source display.
\n
在源显示中需要。
just my 2 cents
只有我的 2 美分
回答by gevra
回答by Geekmoss
Since I have solved basic Markdown, I have resolved the new lines with a regular expression.
由于我已经解决了基本的 Markdown,我已经用正则表达式解决了新行。
import re
br = re.compile(r"(\r\n|\r|\n)") # Supports CRLF, LF, CR
content = br.sub(r"<br />\n", content) # \n for JavaScript
回答by miku
Maybe I don't get it, but isn't <br />
some kind of newline for HTML?
也许我不明白,但不是<br />
某种 HTML 换行符吗?
s = "Hello HTML\n"
to_render = s.replace("\n", "<br />")
If you render something with mimetype "text/plain"
\n
ewlines should work.
如果你用 mimetype "text/plain"
\n
ewlines渲染一些东西应该可以工作。
回答by Martin
Print() should add a newline by default - unless you tell it otherwise. However there have been other changes in Python 3:
Print() 应该默认添加一个换行符 - 除非你另有说明。然而,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.
旧 = Python 2.5,新 = Python 3。
More details here: http://docs.python.org/3.1/whatsnew/3.0.html