python - Python 如何处理字符串的 repr?

标签 python repr

我正在尝试用 Java 完全模拟 Python 的 repr;这包括尽可能使用单引号。 Python 使用什么方法来确定它应该发出哪种类型的引号?

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

最佳答案

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

如图所示:

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

关于python - Python 如何处理字符串的 repr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27464639/

相关文章:

python - with open(filename, "fp") as fp : 的 "w"中 p 代表什么

python - 通用或pythonic __repr__ 方法

python - 在 python 中打印键或值中包含 n 或 t 字符的字典的最佳方法?

python - 数据类字段可以为 repr 格式化它的值吗?

python - 使用 sudo 运行 Django 找不到已安装的 Homebrew 程序包

python:将中间人注入(inject)方法调用

python - 使用 Python unittest 测试回调调用的正确方法是什么?

python - %r 是什么意思?

python - 在 __repr__() 函数中使用 f 字符串时出现 EOF 错误

python - OCR 的 tensorflow 模型