Python 三重字符串引号声明

标签 python string

我按以下方式使用三重字符串:

str="""jeff"""
str=""""jeff"""
str=""""jeff""""   # error
str=""""jeff """"

第三个是错误的,谁能解释为什么这是错误的?

最佳答案

三个引号结束一个字符串,所以这个

str=""""jeff""""

解析为:

str= """ ("jeff) """ (")

尾随引号是问题所在。

顺便说一句,看着 BNF definition

longstring      ::=  "'''" longstringitem* "'''"
                     | '"""' longstringitem* '"""'

很明显,星号 * 是非贪婪的,但我不知道这是否记录在某处。

为了回应评论,这

 str = ''''''''jeff'''

被解释为

(''')(''')('')(jeff)(''') <-- error, two quotes

还有这个

 str = '''''''''jeff'''

被解释为

 str = (''')(''')(''')(jeff)(''') <-- no error, empty string + jeff

关于Python 三重字符串引号声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9290058/

相关文章:

python - 如何用Python进行二维回归分析?

python - PyQt:初始化重置的默认值

python - 提取列表值的一些感兴趣的部分

python - 'soft' 错误的异常处理

string - 字符串内的换行符显示在 TMemoBox 上

Java:字符串等于不适用于innerHTML 文本

javascript - 验证表单而不提交

c++ - 将 char* 数组作为字符串返回 -> 内存泄漏?

.net - 如何在 .NET 中创建特定于域的字符串类?

python - 用简单函数替换类方法