Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Program Runs but can't format the data

Status
Not open for further replies.

canflyguy

Technical User
Jul 25, 2018
100
CA
I'm new to this Python program so I'm experimenting and fighting with syntax and formatting.
I've managed to figure out how to make this program execute and stay running but I can't figure out how to eliminate extra characters in the received data.
When I run it, I get b'GET /8005551212&230' as a response. So how do I strip off the b'GET / and the ' on the end to end up with an editable string like 8005551212&230 or ulimately two strings of 8005551212 and 230 that I can then format into whatever arrangement of extra info that I may add? It gives an error when I leave the line that attempts to convert it to a string and strip off the extra characters: it gives me: TypeError: a bytes-like object is required, not 'str'

Code:
import socket, sys

host = ''               
port = 65432
socksize = 19

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
print("Server started on port: %s" % port)
s.listen(1)
print("Now listening...n")


while True:
    conn, addr = s.accept()
    data = conn.recv(socksize)
    string = data.strip('/') #this line doesn't work
    if not data:             #it gives me: TypeError: a bytes-like object is required, not 'str'
        x=1
    else:
        print(data)
        print(string)
 
to get string from bytes use decode(), to get parts of the string you can use re.split()

example:
Code:
>>> import re
>>> data = b'GET /8005551212&230'
>>> data
b'GET /8005551212&230'
>>> data_str = data.decode()
>>> data_str
'GET /8005551212&230'
>>> data_lst = re.split(r"[/&]", data_str)
>>> data_lst
['GET ', '8005551212', '230']
>>> data_lst[1]
'8005551212'
>>> data_lst[2]
'230'
>>>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top