![](/img/trans.png)
[英]Why does my print statement(python) work in my python 3.4.3 shell, but not the online compiler? Is it because it's a different version?
[英]Why does Python 3.4.3 using lxml not output print statement correctly?
當我嘗試遍歷lxml教程時,我不禁感到奇怪,為什么當我使用print命令時,即使在pretty_print = True的情況下,屏幕上的輸出仍希望將所有內容都放在一行上。
可以這么說,我剛剛安裝了Python 3.4.3 64位,並在安裝了Python之后安裝了lxml-3.4.0.win32-py3.4.exe。
然后,在IDLE或python.exe cmd提示符下,執行以下操作:
from lxml import etree
root = etree.XML('<root><a><b/></a></root>')
print(etree.tostring(root, pretty_print=True))
我(和本教程)期望的是屏幕上的以下輸出:
<root>
<a>
<b/>
</a>
</root>
但是我實際上在Windows 7的IDLE和python cmd提示符下都看到的是:
b'<root>\n <a>\n <b/>\n </a>\n</root>\n'
那么,為什么口譯員要這樣做呢? 有沒有辦法在單行模式和更普通的標准輸出之間切換? 也許更重要的是,如果我想將此XML寫入文件,使用lxml的Python是否會堅持將\\ n和其他所有內容放在一行上,而不是按照預期的方式漂亮地打印出來?
謝謝,約翰尼
您將看到字節字符串的表示形式。 您可以直接將字節寫入文件:
with open("file.xml", "wb") as output:
output.write(etree.tostring(root, pretty_print=True))
print
需要一個unicode字符串,因此您必須編碼為unicode:
print(etree.tostring(root, pretty_print=True, encoding='unicode'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.