我已经升级到 Python 3,但不知道如何将反斜杠转义换行符转换为 HTML。
浏览器按字面呈现反斜杠,因此“ " 对 HTML 源没有影响。结果,我的源页面都是一长行,无法诊断。
通常我喜欢这样
s=s.replace("\n","<br />\n")
因为
网页显示需要<br />
,
源显示中需要\n
。
只是我的2分钱
解决办法是:
#!/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')
请参阅此处的原始讨论: http://groups.google.com/group/comp.lang.python/msg/f8bba45e55fe605c
也许我不明白,但是
<br />
不是 HTML 的某种换行符吗?
s = "Hello HTML\n"
to_render = s.replace("\n", "<br />")
如果您使用 mimetype 渲染某些内容
"text/plain"
\n
ewlines 应该可以工作。
如果您使用 Django,this 答案将会有帮助。
这是关于如何渲染页面以及是否转义 HTML。
既然我已经解决了基本的 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
对我来说,使用Python 3.8.0,在我想要显示到html页面上的字符串中添加字符串
<br />
,然后在utf-8
中编码最终字符串就可以了。看看下面的代码:
min_value = 1
max_value = 10
output_string = "min =" + min_value
output_string += "<br /> max =" + max_value
return output_string.encode('utf-8')
这将输出:
分钟=1
最大=10
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)!
旧= Python 2.5,新= Python 3。