Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't concat bytes to str

Tags:

python

This is proving to be a rough transition over to python. What is going on here?:

f = open( 'myfile', 'a+' ) f.write('test string' + '\n')  key = "pass:hello" plaintext = subprocess.check_output(['openssl', 'aes-128-cbc', '-d', '-in', test, '-base64', '-pass', key]) print (plaintext)  f.write (plaintext + '\n') f.close() 

The output file looks like:

test string

and then I get this error:

b'decryption successful\n' Traceback (most recent call last):   File ".../Project.py", line 36, in <module>     f.write (plaintext + '\n') TypeError: can't concat bytes to str 
like image 466
AndroidDev Avatar asked Feb 20 '14 18:02

AndroidDev


People also ask

Can t concat bytes to str?

The Python "TypeError: can't concat str to bytes" occurs when we try to concatenate a bytes object and a string. To solve the error, decode the bytes object into a string before concatenating the strings.

Can only concatenate str not bytes to str?

The Python "TypeError: can only concatenate str (not "bytes") to str" occurs when we try to concatenate a string and a bytes object. To solve the error, decode the bytes object into a string before concatenating the strings.

How do you concatenate bytes and strings in Python?

Python concatenate strings and bytes To concatenate strings and bytes we will use the + operator to concatenate, and also we use str() to convert the bytes to string type, and then it will be concatenated. To get the output, I have used print(my_str + str(bytes)).


1 Answers

subprocess.check_output() returns a bytestring.

In Python 3, there's no implicit conversion between unicode (str) objects and bytes objects. If you know the encoding of the output, you can .decode() it to get a string, or you can turn the \n you want to add to bytes with "\n".encode('ascii')

like image 147
Wooble Avatar answered Sep 29 '22 00:09

Wooble