TypeError: can't convert 'str' object to str implicitly
Andrea Filippini last edited by
What does exactly mean this error? I'm confused
@robert-hh my bad, you're right
>>> type(s.split(b'|')) <class 'bytes'> >>> type(str(s).split('|')) <class 'str'>
robert-hh last edited by
@PiAir split() always returns a list. You'll see a difference with type(sp).
@robert-hh it works but gives a different result:
>>> sp = s.split(b'|') >>> type(sp) <class 'list'>
robert-hh last edited by robert-hh
sp = s.split(b'|')
works too. The difference is, that in the error case you mix string and bytes objects. The conversion you apply in your working examples you show convert the bytes object to string, and the split with a string works.
P.S.: I would say that the error message is misleading.
s = b'foo|bar'
The variable s that you create is of type byte, while split() is intended to be used on variables of type str (string).
The other two code fragments that you provide first convert the byte to a string before split() is applied.
Take a look at this:
>>> s = b'foo|bar' >>> type(s) <class 'bytes'> >>> s2 = str(s) >>> type(s2) <class 'str'> >>> s3= s.decode('utf-8') >>> type (s3) <class 'str'>
the type() function gives you the type of an object/variable. You can see that .decode() and str() causes the byte object to be converted explicitly to a string (instead of implicitly expecting that that is being done for you by using split() on a byte object).
Hope this explains it?
Andrea Filippini last edited by Andrea Filippini
@bucknall My question is not really relative to a piece of code in particular, but here's an example:
s = b'foo|bar' sp = s.split('|')
s = b'foo|bar' sp = str(s).split('|')
and this works
s = b'foo|bar' sp = s.decode('utf-8').split('|')
Please explain the difference
bucknall last edited by
Could you please share the code that caused this error?