2016-06-14 112 views
-4

代碼:蟒蛇新行(字節字符串)

word="hello\nhai" 
fout=open("sample.txt","w"); 
fout.write(word); 

輸出:

hello 
hai 

但這:

word=b"hello\nhai" 
str_word=str(word)      # stripping ' '(quotes) from byte 
str_word=str_word[2:len(str_word)-1] # and storing just the org word 
fout=open("sample.txt","w"); 
fout.write(str_word); 

輸出:

hello\nhai 

代碼中的問題是什麼?

我正在通過Python中的端口發送和接收字符串。由於只有字節可以發送和接收,所以我有上述問題。但爲什麼會發生?

+2

'STR(字節)'不字節的字符串翻譯。改用'bytes.decode()'。 – syntonym

+0

非常感謝 –

回答

1

寫字節以二進制方式:

word=b"hello\nhai" 
with open("sample.txt","wb") as fout: 
    fout.write(word); 

您還可以將原始字符串編碼爲字節:

word="hello\nhai".encode()