【问题标题】:forloop TypeError: can't concat str to bytesforloop TypeError:无法将 str 连接到字节
【发布时间】:2019-11-23 03:29:55
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    错误状态: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))
    

    更新:修正格式的拼写

    【讨论】:

    • 我认为诀窍是将 int 编码为字节。感谢您的帮助
    【解决方案2】:

    我处理了同样的问题,上面的代码用 .enconde('ascii') 解决了这个问题

    【讨论】:

      【解决方案3】:
      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")
      

      这可能会奏效...希望对您有所帮助

      【讨论】:

      • 请编辑您的答案,使代码显示为这样。此外,只发布您测试过的答案。一段“可能会成功”的代码不是答案。如果您在您的环境中验证了代码,但不确定 OP 的环境是否会产生相同的结果,请使用您的环境的详细信息来限定您的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      相关资源
      最近更新 更多