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 ' '(quote
Solution 1:
I am working on sending and receiving strings over a port. As only bytes can be sent and received I have the above problem.
.encode()
strings to create bytes. .decode()
bytes to get strings. The default encoding is UTF-8, which can handle all characters in a string.
If you have bytes, write them in binary mode:
word = b"hello\nhai"# byteswithopen("sample.txt","wb") as fout: # (w)rite (b)ytes
fout.write(word);
If writing to a port that only takes bytes (you didn't mention the port function, so only an example):
port.write(b'hello')
or:
port.write('hello'.encode())
Reading:
string_result = port.read().decode()
Post a Comment for "Python New Line (byte To String)"