TypeError: can't convert 'str' object to str implicitly
-
What does exactly mean this error? I'm confused
-
Python makes a clear distinction between bytes and strings . Bytes objects contain raw data — a sequence of octets — whereas strings are Unicode sequences . Conversion between these two types is explicit: you encode a string to get bytes, specifying an encoding (which defaults to UTF-8); and you decode bytes to get a string. Clients of these functions should be aware that such conversions may fail, and should consider how failures are handled.
We can convert bytes to string using bytes class decode() instance method, So you need to decode the bytes object to produce a string. In Python 3 , the default encoding is "utf-8" , so you can use directly:
b"python byte to string".decode("utf-8")
-
This post is deleted!
-
@robert-hh my bad, you're right
>>> type(s.split(b'|')[0]) <class 'bytes'> >>> type(str(s).split('|')[0]) <class 'str'>
-
@PiAir split() always returns a list. You'll see a difference with type(sp[0]).
-
@robert-hh it works but gives a different result:
>>> sp = s.split(b'|') >>> type(sp) <class 'list'>
-
@Andrea-Filippini
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.
-
@Andrea-Filippini said in TypeError: can't convert 'str' object to str implicitly:
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?
-
@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('|')
while this
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
-