繁体   English   中英

python新行(字节到字符串)

[英]python new line (byte to string)

码:

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中的端口发送和接收字符串。 由于只能发送和接收字节,所以我遇到了上述问题。 但是为什么会发生呢?

以二进制模式写入字节:

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

您还可以将原始字符串编码为字节:

word="hello\nhai".encode()

暂无
暂无

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

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