Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

python new line (byte to string)

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...