forloop TypeError: can't concat str to bytes

forloop TypeError: can't concat str to bytes

我是 python3 的新手,试图将 python 2.7 代码转换为 python 3,但我遇到了这个问题。让我知道我哪里错了。

for n in range (755,767):
    tn.write(b"vlan " + str(n) + "\n")
    tn.write(b"name Python_VLAN_" + str(n) + "\n")

错误:

Traceback (most recent call last):
  File "./telnetlib_vlan_loop.py", line 30, in <module>
    tn.write(b"vlan " + str(n) + "\n")
TypeError: can't concat str to bytes**strong text**

错误状态:TypeError: can't concat str to bytes

您当前的问题是您有 bytesstr,并且您正试图将它们加在一起。您需要先使用相同的类型。

如果您需要写成 strbytes

,您没有提供

如果 bytes 将代码更改为:

for n in range (755,767): 
    tn.write("vlan {}\n".format(n).encode()) 
    tn.write("name Python_VLAN_{}\n".format(n).encode())

如果 str 只需删除 encode

for n in range (755,767): 
    tn.write("vlan {}\n".format(n)) 
    tn.write("name Python_VLAN_{}\n".format(n))

更新:修复了格式的拼写问题

for n in range(755,767):
    tn.write(b"vlan " + str(n).encode('ascii') + b"\n")
    tn.write(b"name Python_VLAN_" + str(n).encode('ascii') + b"\n")

这可能有用...希望对您有所帮助

我处理了同样的问题,并使用上面的代码修复了

中的 .encode('ascii')