python新行(字节到字符串)

时间:2016-06-14 13:35:26

标签: python

代码:

spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false

输出:

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

代码中有什么问题?

我正在通过python中的端口发送和接收字符串。由于只能发送和接收字节,我有上述问题。但为什么会发生呢?

1 个答案:

答案 0 :(得分:1)

以二进制模式写入字节:

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

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

word="hello\nhai".encode()