简体   繁体   English

Python如何处理字符串的repr?

[英]How does Python handle repr for strings?

I'm trying to emulate Python's repr exactly in Java; 我正在尝试完全在Java中模拟Python的repr。 this includes the use of single quotes where possible. 这包括在可能的情况下使用单引号。 What method does Python use to determine what sort of quotes it should emit? Python使用哪种方法来确定应该发出什么样的引号?

Edit: I'm looking for some actual code, somewhere in the web of Python. 编辑:我正在寻找一些实际的代码,在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. 我已经看过Objects/unicodeobject.c和一些Objects/strlib/ ,但是除了Unicode的转义序列外,我什么也找不到。

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 \'

https://github.com/python/cpython/tree/master/Objects/unicodeobject.c 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. unicode_repr在这里github.com/python/cpython/blob/master/Objects/unicodeobject.c的外观。

NOTE: I've updated this answer to remove out-of-date info and point to the current repo 注意:我已经更新了此答案,以删除过时的信息并指向当前回购

From what I could extract out of Objects/byteobject.c ( here ), this is the section that does it: 从我可以从Objects/byteobject.c提取的Objects/byteobject.c此处 )中,这是执行此操作的部分:

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. 因此,如果没有双引号并且有单引号,则使用双引号,否则使用单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM