TypeError: can only concatenate str (not "bytes") to str in Python

Dung Do Tien Oct 08 2021 145

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have some lines of code and I want to mix bytes datatype with some other operator and bytes characters. My block of code as below:

symbol = b'j|encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004'

sum_text = '\xff' * 5 + symbol * 10

print(sum_text)

But I get an exception throw TypeError: can only concatenate str (not "bytes") to str when I run code above.

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    sum_text = '\xff' * 5 + symbol * 10
TypeError: can only concatenate str (not "bytes") to str

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.
  • W

    Watcharapong Jakkawannorasing Oct 08 2021

    You can't concat string with byte data type. I sure you miss it. Please change line code:

    sum_text = '\xff' * 5 + symbol * 10

    To

    sum_text = b'\xff' * 5 + symbol * 10

    And it work for you.

  • A

    Anand Pissey Oct 08 2021

    Change '\xff' to b'\xff' and it work for you.

    symbol = b'j|encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004'
    
    sum_text = b'\xff' * 5 + symbol * 10
    
    print(sum_text)

    #Output

    b'\xff\xff\xff\xff\xffj|encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004j|encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004j
    |encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004j|encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004j|encoding: hexdump emoji.txt0000000 
    f0 9f 98 ae 0000004j|encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004j|encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004j
    |encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004j|encoding: hexdump emoji.txt0000000 f0 9f 98 ae 0000004j|encoding: hexdump 
    emoji.txt0000000 f0 9f 98 ae 0000004'

    I hope it 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