Reputation: 4296
I'm trying to emulate Python's repr exactly in Java; this includes the use of single quotes where possible. What method does Python use to determine what sort of quotes it should emit?
Edit: I'm looking for some actual code, somewhere in the web of Python. I've already looked at Objects/unicodeobject.c
and some of Objects/strlib/
, but I couldn't find anything besides escape sequences for Unicode.
Upvotes: 2
Views: 176
Reputation: 7538
https://github.com/python/cpython/tree/master/Objects/unicodeobject.c
static PyObject *
unicode_repr(PyObject *unicode)
{ ...
unicode_repr in here github.com/python/cpython/blob/master/Objects/unicodeobject.c by the looks of it.
NOTE: I've updated this answer to remove out-of-date info and point to the current repo
Upvotes: 1
Reputation: 4296
From what I could extract out of Objects/byteobject.c
(here), this is the section that does it:
quote = '\'';
if (smartquotes && squotes && !dquotes)
quote = '"';
if (squotes && quote == '\'') {
if (newsize > PY_SSIZE_T_MAX - squotes)
goto overflow;
newsize += squotes;
}
So, if there is no double quotes and there is single quotes it uses double quotes, otherwise single quotes.
Upvotes: 1
Reputation: 3587
I guess it will use single quotes unless it need to use it inside the string.
As show in:
print repr("Hello")
print repr('Hello')
print repr("Hell'o")
print repr('Hell"o')
print repr("""Hell'o Worl"o""")
Output:
'Hello'
'Hello'
"Hell'o" # only one using double quotes
'Hell"o'
'Hell\'o Worl"o' # handles the single quote with a \'
Upvotes: 1