Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Code:

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

Output:

hello
hai

But this:

word=b"hello
hai"
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
hai

What is the problem in the code?

I am working on sending and receiving strings over a port in python. As only bytes can be sent and received I have the above problem. But why does it occur?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
190 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
hai"  # bytes
with open("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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...