Exception typeerror: can't concat int to bytes in Python

Dung Do Tien Oct 09 2021 142

Hello you guys, I beginner in Python and I'm also studying more about Python.

I write some line of code, it help me concat some bytes and integer get from user input. My block of code as below:

symbol = b'j|encoding: hexdump'
play_symbol = b'emoji.txt0000000 f0'
bonus_number = int(input("Enter bonus number:"))

full_text = symbol + play_symbol + bonus_number

print(full_text)

But I get an exception throw TypeError: can't concat int to bytes when I run code above.

Enter bonus number:5
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    full_text = symbol + play_symbol + bonus_number
TypeError: can't concat int to bytes

And I am using python 3.8.2

Anyone can explain exception to me? And how can I solve it?

Thanks for any suggestions.

Have 2 answer(s) found.
  • Đ

    Đặng Thanh Tuấn Oct 09 2021

    You can see error throw from below line of code:

    full_text = symbol + play_symbol + bonus_number

    Because bytes is NOT allow addition with integer. So you can solve by choose one way below:

    1. Using bytes() method to help convert int to byte.

    full_text = symbol + play_symbol + bytes(bonus_number)

    #Output

    Enter bonus number:5
    b'j|encoding: hexdumpemoji.txt0000000 f0\x00\x00\x00\x00\x00'

    2. Using multiply operator between byte and integer.

    full_text = (symbol + play_symbol) * bonus_number

    #Output

    Enter bonus number:5
    b'j|encoding: hexdumpemoji.txt0000000 f0j|encoding: hexdumpemoji.txt0000000 f0j|
    encoding: hexdumpemoji.txt0000000 f0j
    |encoding: hexdumpemoji.txt0000000 f0j|encoding: hexdumpemoji.txt0000000 f0
    
  • H

    Hieu Nguyen Oct 09 2021

    To solve this issue, you can change:

    full_text = symbol + play_symbol + bonus_number

    To

    full_text = symbol + play_symbol + bytes(bonus_number)

    And it worked 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