[英]How to get Python to make new lines in a print statement with \r\n?
現在,我正在編寫python SMTP腳本。
status = clientSocket.recv(1024)
print (status)
當python打印status
,我得到:
b'250-mx.google.com at your service, [107.216.175.252]\r\n250-SIZE 35882577\r\n250-8BITMIME\r\n250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN\r\n250-ENHANCEDSTATUSCODES\r\n250 CHUNKING\r\n'
但是,我希望python將\\r\\n
轉換為實際的新行,而不僅僅是將其打印為一條巨型行。 我將如何去做呢?
>>> print(status.decode())
250-mx.google.com at your service, [107.216.175.252]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN
250-ENHANCEDSTATUSCODES
250 CHUNKING
您正在使用默認為unicode的Python 3,但是您在執行套接字時使用了舊式字節字符串。 您只需要decode
它,然后print
就會照常擺脫換行符。
status
具有字節類型,因此您需要將其解碼為字符串。
實現此目的的2種明顯方法:
print(status.decode())
print(str(status, 'utf-8'))
.decode
的默認編碼為UTF-8,因此,如果要使用其他status.decode(encoding)
,請執行status.decode(encoding)
。 並且status.decode(encoding)
與str(status, encoding)
完全等效。
為什么只是str(status)
無法正常工作:
在沒有編碼或錯誤參數的情況下將字節對象傳遞給str()屬於返回非正式字符串表示形式的第一種情況。 例如:
>>> str(b'Zoot!')
"b'Zoot!'"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.