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
2.0k views
in Technique[技术] by (71.8m points)

python - can only concatenate str (not "bytes") to str

import socket
import os

user_url = input("Enter url: ")

host_name = user_url.split("/")[2]
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((host_name, 80))
cmd = 'GET ' + user_url + ' HTTP/1.0

'.encode()
mysock.send(cmd)

while True:
    data = mysock.recv(512)
    if len(data) < 1:
        break
     print(data.decode(),end='
')

mysock.close()

For some reason im gettin this error

Enter url: http://data.pr4e.org/romeo.txt

 7 mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 8 mysock.connect((host_name, 80))
 9 cmd = 'GET ' + user_url + ' HTTP/1.0

'.encode()
 TypeError: can only concatenate str (not "bytes") to str

Any ideas what im doing wrong with it?Encoding and decoding seems right to me, and i've trasnfered it using before .encode(). This is for a class

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A str is an abstract sequence of Unicode code points; a bytes is a sequence of 8-bit numbers. Python 3 made the distinction between the two very clear and does not allow you to combine them implicitly. A str may have several valid encodings, and a bytes object may or may not be the encoding of a valid Unicode string. (Or, the bytes could be the encoding of multiple different str objects depending on the encoding used to create it.)

'GET ' and user_url are str objects, while ' HTTP/1.0 '.encode() is a bytes object. You want to encode the entire concatenated string instead.

cmd = 'GET {} HTTP/1.0

'.format(user_url).encode()

Or perhaps written to show the steps more clearly,

cmd = 'GET {} HTTP/1.0

'.format(user_url)  # still a str
mysock.send(cmd.encode())  # send the encoding of the str

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

...