Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Program Runs but can't format the data

Program Runs but can't format the data

Program Runs but can't format the data

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'

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

RE: Program Runs but can't format the data

to get string from bytes use decode(), to get parts of the string you can use re.split()



>>> 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]
>>> data_lst[2]

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close