TypeError: decoding str is not supported (converting bytes into str)

11,853

You've already converted that name to a str.

The line

self.name_list.append(str(name, 'utf-8'))

converts the name to a string and saves it a list.

Then

for name in self.name_list:

loops over those names, and at the end of the for loop the value of name is the final converted name in self.name_list.

So when you do

strftime("%Y-%m-%d %H:%M:%S", gmtime())+" "+str(name, 'utf-8')+ " is connected")

It's using that name, not the raw one returned by name = c.recv(1024)

The simple solution is to use a different variable name in that for loop which processes self.name_list.

Share:
11,853

Related videos on Youtube

HI YUM
Author by

HI YUM

Updated on June 04, 2022

Comments

  • HI YUM
    HI YUM almost 2 years

    I have this code

    def run(self):
        while True:
            c, a = self.sock.accept()
            print(c)
            name = c.recv(1024)
            people = ""
            self.name_list.append(str(name, 'utf-8'))
            num_g = len(self.name_list)
            c.send(bytes(str(num_g), 'utf-8'))
            print((str(num_g)))
    
            data = str(c.recv(1024), 'utf-8')
            print(data)
            if str(data) == "ok":
                for name in self.name_list:
                    print(name)
                    c.send(bytes(name, 'utf-8'))
            print(len(self.name_list))
            print(strftime("%Y-%m-%d %H:%M:%S", gmtime())+" "+str(name, 'utf-8')+ " is connected")
    

    and i get this error

        File "./server.py", line 51, in run
        print(strftime("%Y-%m-%d %H:%M:%S", gmtime())+" "+str(name, 'utf-8')+ " is connected")
    TypeError: decoding str is not supported
    

    i don't understand why i get this error. when i receive the bytes from connection,

    name = c.recv(1024)
    

    the name is in bytes, that's why i tried to make it string when i print that line

    • Rakesh
      Rakesh almost 6 years
      try print("{0} {1} is connected".format(strftime("%Y-%m-%d %H:%M:%S", gmtime()), name)