2016-06-14 3 views
-4

コード:pythonの新しい行(文字列へのバイト)

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() 
関連する問題