[英]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.