'Join bytes into one string in python
I have the following function that sends a string from ESP32 to Raspberry:
def rx_and_echo():
sock.send("\nsend anything\n")
while True:
data = sock.recv(buf_size)
if data:
print(data)
sock.send(data)
The format received by Raspberry is as follow:
b'T'
b'e'
b'x'
b't'
How to convert it into just Text?
Solution 1:[1]
you can keep the data Rx and keep pushing element by element instead of the list here:
lst = [b'T',b'e',b'x',b't']
x = ''.join([""+st.decode("utf-8") for st in lst])
sock.send(x)
#to have data as a list from socket
data_list = []
while True:
data = sock.recv(buf_size)
if data:
#for certain length of data you want to accumulate and then send
if len(data_list)>3:
msg = ''.join([""+st.decode("utf-8") for st in data_list])
sock.send(msg)
data_list = []
else:
data_list.append(data)
Output:
Text
Solution 2:[2]
Something like this maybe?
def rx_and_echo():
sock.send("\nsend anything\n")
res = ''
while True:
data = sock.recv(buf_size)
if data:
res += data.decode()
sock.send(res)
Edit: Actually, that doesn't seem right. What exactly does sock.recv return? Does this help?
def rx_and_echo():
sock.send("\nsend anything\n")
res = ''
for b in sock.recv(buf_size)
res += b.decode()
sock.send(res)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
