Throw typeerror: can't concat float to bytes in Python 3.x
Hello you guys, I beginner in Python and I'm also studying more about Python.
I have some lines of code to help me concat more bytes data type from some variables and plus them with a float number. My block of code as below:
symbol = b'j|encoding: hexdump'
symbol2 = b'emoji.txt0000000 f0'
symbol3 = b'9f 98 ae 0000004'
sum_text = symbol + symbol2 + b'\xff' + symbol3 + 2.5
print(sum_text)
But I get an exception throw TypeError: can't concat float to bytes when I run code above.
Traceback (most recent call last):
File "main.py", line 5, in <module>
sum_text = symbol + symbol2 + b'\xff' + symbol3 + 2.5
TypeError: can't concat float to bytes
And I am using python 3.8.2
Anyone can explain it to me? How can I solve it?
Thanks for any suggestions.
-
s0
sirpa sricharan Oct 09 2021
You can NOT concat/plus
bytes
withfloat
ordouble
data type.Bytes
data type only multiple withinteger
.For example:
symbol = b'j|encoding: hexdump' symbol2 = b'emoji.txt0000000 f0' symbol3 = b'9f 98 ae 0000004' sum_text = symbol + symbol2 + b'\xff' + symbol3 * 2 print(sum_text)
#Output
b'j|encoding: hexdumpemoji.txt0000000 f0\xff9f 98 ae 00000049f 98 ae 0000004'
I think you need to learn more a bout datatype in Python.
-
s0
shruti sarva Oct 09 2021
symbol3 + 2.5
is wrong. The bytes data type is not allowaddition
with float number.- Only addition
byte
withbyte
- And multiply
byte
withinteger
So to fix your issue you can change:
sum_text = symbol + symbol2 + b'\xff' + symbol3 + 2.5
To
sum_text = symbol + symbol2 + b'\xff' + symbol3 * 2 // Change addition to multiply and float to integer. OR sum_text = symbol + symbol2 + b'\xff' + symbol3 // Remove addition float number.
I hope it's useful for you.
- Only addition
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.