Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert input () to bytes in Python 3? [duplicate]

Since I started using version 3 of Python I have had many problems with sending string through sockets. I know that to send a string in a socket, a 'b' must be placed before the string to convert it to bytes. But what happens when I have to convert an input() to bytes? How is it done?

I need to send a message written by keyboard to a socket:

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost",7500))

msg = input()
client.send(msg) 

However, when I try it, I get the following error:

TypeError: a bytes-like object is required, not 'str'

Can someone tell me how I convert input() to bytes? I always use version 2.7 and I do not understand why version 3 is so irritating for the handling of sockets. :(

like image 337
Jhonatan Zu Avatar asked Dec 18 '25 10:12

Jhonatan Zu


2 Answers

You need to encode you message like this:

msg = input().encode()

The reason you did not need to do this in Python 2 is because unicode strings were then their own type, but in Python 3 all strings are now unicode by default.

like image 156
Olivier Melançon Avatar answered Dec 20 '25 00:12

Olivier Melançon


To do that, you can use

import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost",7500))
msg = input()
client.send(msg.encode())

It returns the string encoded as a bytes object. See str.encode

like image 40
juancarlos Avatar answered Dec 19 '25 23:12

juancarlos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!