2016-06-14 97 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()