Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Descriptor 'split' requires a 'str' object but received a 'unicode'

Tags:

python

Erm, I have ready-to-use code, and I'm sure it really works, but I get the following error:

TypeError: descriptor 'split' requires a 'str' object but received a 'unicode'

That's the whole def:

def assemblePacket(self, type):
    ipSplit = str.split(self.serverVars[0], '.')

    packet = 'SAMP'
    packet += chr(int(ipSplit[0]))
    packet += chr(int(ipSplit[1]))
    packet += chr(int(ipSplit[2]))
    packet += chr(int(ipSplit[3]))
    packet += chr(self.serverVars[1] & 0xFF)
    packet += chr(self.serverVars[1] >> 8 & 0xFF)
    packet += type

    return packet

And here is the problem:

ipSplit = str.split(self.serverVars[0], '.')

I'm sure it's not because of the code, I've tried it before (the same script) and it worked. No idea why it doesn't now.And this "unicode" makes me think I have to change "str.split", but hmmm. Waiting for opinions :)

like image 236
Tom Jenkins Avatar asked Dec 31 '12 07:12

Tom Jenkins


2 Answers

The problem is that str.split is a method of the str class, but is being called for an object of the unicode class. Call the method directly with ipSplit = self.serverVars[0].split('.') to have it work for anything (including str and unicode) with a split method.

like image 190
Abe Karplus Avatar answered Oct 23 '22 19:10

Abe Karplus


As @Abe mentioned, the problem here is, you are using str.split to split an object of type unicode which is causing the failure.

There are three options for you

  1. In this particular case, you can simply call the split() method for the object. This will ensure that irrespective of the type of the object (str, unicode), the method call would handle it properly.
  2. You can also call unicode.split(). This will work well for unicode string but for non-unicode string, this will fail again.
  3. Finally, you can import the string module and call the string.split function. This function converts the split() function call to method call thus enabling you to transparently call the split() irrespective if the object type. This is beneficial when you are using the split() as callbacks esp to functions like map()
like image 42
Abhijit Avatar answered Oct 23 '22 19:10

Abhijit