2

我正在尝试在 Java 中完全模拟 Python 的 repr;这包括在可能的情况下使用单引号。Python 使用什么方法来确定它应该发出什么样的引号?

编辑:我正在寻找一些实际的代码,在 Python 网络的某个地方。我已经查看了Objects/unicodeobject.c一些Objects/strlib/,但除了 Unicode 的转义序列之外我找不到任何东西。

4

3 回答 3

1

从我可以从Objects/byteobject.chere)中提取的内容中,这是执行此操作的部分:

quote = '\'';
if (smartquotes && squotes && !dquotes)
    quote = '"';
if (squotes && quote == '\'') {
    if (newsize > PY_SSIZE_T_MAX - squotes)
        goto overflow;
    newsize += squotes;
}

因此,如果没有双引号而有单引号,则使用双引号,否则使用单引号。

于 2014-12-14T00:15:19.527 回答
1

https://github.com/python/cpython/tree/master/Objects/unicodeobject.c

static PyObject *
unicode_repr(PyObject *unicode)
{ ...

unicode_repr 在这里 github.com/python/cpython/blob/master/Objects/unicodeobject.c 看起来。

注意:我已经更新了这个答案以删除过时的信息并指向当前的 repo

于 2014-12-13T23:53:30.007 回答
1

我猜它会使用单引号,除非它需要在字符串中使用它。

如图所示:

print repr("Hello")
print repr('Hello')
print repr("Hell'o")
print repr('Hell"o')
print repr("""Hell'o Worl"o""")

输出:

'Hello'
'Hello'
"Hell'o" # only one using double quotes
'Hell"o'
'Hell\'o Worl"o' # handles the single quote with a \'
于 2014-12-13T23:21:38.917 回答