简体   繁体   English

python新行(字节到字符串)

[英]python new line (byte to string)

Code: 码:

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

Output: 输出:

hello
hai

But this: 但是这个:

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);

Outputs: 输出:

hello\nhai

What is the problem in the code? 代码有什么问题?

I am working on sending and receiving strings over a port in python. 我正在通过python中的端口发送和接收字符串。 As only bytes can be sent and received I have the above problem. 由于只能发送和接收字节,所以我遇到了上述问题。 But why does it occur? 但是为什么会发生呢?

Write the bytes in binary mode: 以二进制模式写入字节:

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

You can also encode the original string to bytes: 您还可以将原始字符串编码为字节:

word="hello\nhai".encode()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM