Throw typeerror: can't concat float to bytes in Python 3.x

Dung Do Tien Oct 09 2021 123

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.

Have 2 answer(s) found.
  • s

    sirpa sricharan Oct 09 2021

    You can NOT concat/plus bytes with float or double data type.

    Bytes data type only multiple with integer.

    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.

  • s

    shruti sarva Oct 09 2021

    symbol3 + 2.5 is wrong. The bytes data type is not allow addition with float number. 

    1. Only addition  byte with byte
    2. And multiply byte with integer

    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.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close