Search code examples
pythonpython-3.xfor-loopciscotelnetlib

forloop TypeError: can't concat str to bytes


I am new to python3, trying to convert python 2.7 code to python 3, and I get into this issue. Let me know where I am wrong.

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

Error:

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

Solution

  • Error states: TypeError: can't concat str to bytes

    Your current issue is that you have bytes and str and you are trying to add them together. You need to use the same type prior to do so.

    You are not providing if you need to write as str or bytes

    If bytes change your code to:

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

    If str just remove the encode

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

    Update: fixed spelling of format