Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to a buffer in Python 3.1?

I am attempting to pipe something to a subprocess using the following line:

p.communicate("insert into egg values ('egg');");

TypeError: must be bytes or buffer, not str

How can I convert the string to a buffer?

like image 945
David Avatar asked Feb 01 '10 12:02

David


People also ask

How do I convert a string to a number in Python 3?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do you convert string to in python?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.

Which Python method is used to convert values to strings?

We can convert numbers to strings through using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.

How do you convert text to raw text in Python?

Use the built-in function repr() to convert normal strings into raw strings. The string returned by repr() has ' at the beginning and the end. Using slices, you can get the string equivalent to the raw string.


1 Answers

The correct answer is:

p.communicate(b"insert into egg values ('egg');");

Note the leading b, telling you that it's a string of bytes, not a string of unicode characters. Also, if you are reading this from a file:

value = open('thefile', 'rt').read()
p.communicate(value);

The change that to:

value = open('thefile', 'rb').read()
p.communicate(value);

Again, note the 'b'. Now if your value is a string you get from an API that only returns strings no matter what, then you need to encode it.

p.communicate(value.encode('latin-1');

Latin-1, because unlike ASCII it supports all 256 bytes. But that said, having binary data in unicode is asking for trouble. It's better if you can make it binary from the start.

like image 78
Lennart Regebro Avatar answered Oct 06 '22 12:10

Lennart Regebro