forloop TypeError:无法连接str到字节

时间:2019-07-13 20:31:51

标签: python python-3.x for-loop cisco telnetlib

我是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**

3 个答案:

答案 0 :(得分:2)

错误状态: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".formate(n).encode())

如果str仅删除encode

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

答案 1 :(得分:1)

我处理相同的问题,并且上述代码都通过.enconde('ascii')解决了这两个问题

答案 2 :(得分:0)

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

这可能会达到目的...希望有帮助