只能将str(不是“ bytes”)连接到str [英] can only concatenate str (not "bytes") to str

查看:72
本文介绍了只能将str(不是“ bytes”)连接到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\r\n\r\n'.encode()
mysock.send(cmd)

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

mysock.close()

出于某种原因,我会收到此错误

For some reason im gettin this error


输入网址: http://data.pr4e.org/romeo.txt



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\r\n\r\n'.encode()
 TypeError: can only concatenate str (not "bytes") to str


任何想法我做错了什么?编码和解码似乎正确对我来说,我在.encode()之前使用\n进行了转移。
这是一个类

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

推荐答案

A str 是Unicode代码点的抽象序列; bytes 是8位数字的序列。 Python 3非常清楚地区分了两者,并且不允许您隐式组合它们。 str 可能具有几种有效的编码,并且 bytes 对象可能会也可能不会有效Unicode字符串的编码。 (或者, bytes 可能是多个不同 str 对象的编码,具体取决于

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' user_url str 对象,而'HTTP / 1.0\r\n\r\n'.encode()个字节对象。您想改为编码整个串联的字符串。

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

cmd = 'GET {} HTTP/1.0\r\n\r\n'.format(user_url).encode()

或者写来显示步骤更清晰

Or perhaps written to show the steps more clearly,

cmd = 'GET {} HTTP/1.0\r\n\r\n'.format(user_url)  # still a str
mysock.send(cmd.encode())  # send the encoding of the str

这篇关于只能将str(不是“ bytes”)连接到str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆