Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get str repr with double quotes Python

Tags:

I'm using a small Python script to generate some binary data that will be used in a C header.

This data should be declared as a char[], and it will be nice if it could be encoded as a string (with the pertinent escape sequences when they are not in the range of ASCII printable chars) to keep the header more compact than with a decimal or hexadecimal array encoding.

The problem is that when I print the repr of a Python string, it is delimited by single quotes, and C doesn't like that. The naive solution is to do:

'"%s"'%repr(data)[1:-1]

but that doesn't work when one of the bytes in the data happens to be a double quote, so I'd need them to be escaped too.

I think a simple replace('"', '\\"') could do the job, but maybe there's a better, more pythonic solution out there.

Extra point:

It would be convenient too to split the data in lines of approximately 80 characters, but again the simple approach of splitting the source string in chunks of size 80 won't work, as each non printable character takes 2 or 3 characters in the escape sequence. Splitting the list in chunks of 80 after getting the repr won't help either, as it could divide escape sequence.

Any suggestions?

like image 909
fortran Avatar asked Nov 04 '09 16:11

fortran


People also ask

How do you enclose a string in Python with double quotes?

Quotes in strings are handled differently There is no problem if you write \" for double quotes " . In a string enclosed in double quotes " , single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \" .

How do you print 3 double quotes in Python?

To create strings that span multiple lines, triple single quotes ''' or triple double quotes """ are used to enclose the string. ''' This string is on multiple lines within three single quotes on either side. '''

Can you use double quotation marks in Python?

A string as a sequence of characters not intended to have numeric value. In Python, such sequence of characters is included inside single or double quotes. As far as language syntax is concerned, there is no difference in single or double quoted string. Both representations can be used interchangeably.

How do you mention double quotes in a string?

To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark. For example, to create the preceding string, use the following code.

How to remove double quotes from a string in Python?

This method removes all the occurrences of double quotes (“) from a string. Make sure that you use single quotes (‘) to enclose double quotes in replace () function. Otherwise, it’ll throw an error. Whenever we print a list or string in Python, we generally use str ( ) because of which we have single quotes in the output we get.

What is a quotation string in Python?

Strings in Python are basically, words we put between two quotation marks ‘ ‘ or ” “. There are two methods of representing these strings: Single quote [‘ ‘] Double quotes [” “]

What is the difference between str() and repr() in Python?

Although repr () and str () both return a similar-looking string, the style of the content within the string is different. str () returns an easily readable unofficial string while repr () returns an official univocal string. We say official because the string produced by the repr () function can be later used as an argument for the eval function.

Why does __repr__ have double quotes around its return value?

__repr__ is usually constructed in such a way, that when you pass its return value to eval, you would receive the exact same object __repr__ was defined on in the first place. Hence the double quotes around the single-quoted string, as eval ("'My string'") would work, but eval ('my string') would raise a SyntaxError. See also here


2 Answers

You could try json.dumps:

>>> import json
>>> print(json.dumps("hello world"))
"hello world"

>>> print(json.dumps('hëllo "world"!'))
"h\u00ebllo \"world\"!"

I don't know for sure whether json strings are compatible with C but at least they have a pretty large common subset and are guaranteed to be compatible with javascript;).

like image 177
coldfix Avatar answered Sep 22 '22 23:09

coldfix


Better not hack the repr() but use the right encoding from the beginning. You can get the repr's encoding directly with the encoding string_escape

>>> "naïveté".encode("string_escape")
'na\\xc3\\xafvet\\xc3\\xa9'
>>> print _
na\xc3\xafvet\xc3\xa9

For escaping the "-quotes I think using a simple replace after escape-encoding the string is a completely unambiguous process:

>>> '"%s"' % 'data:\x00\x01 "like this"'.encode("string_escape").replace('"', r'\"')
'"data:\\x00\\x01 \\"like this\\""'
>>> print _
"data:\x00\x01 \"like this\""
like image 31
u0b34a0f6ae Avatar answered Sep 21 '22 23:09

u0b34a0f6ae