【发布时间】:2015-08-15 12:27:30
【问题描述】:
我刚刚发现我认为是一个错字,但 Python 接受了它。
foo = {'a': 'b'}
foo.get('a'"")
返回'b'。在 Python 中,'a'"" 在哪里定义为函数的有效参数?
【问题讨论】:
我刚刚发现我认为是一个错字,但 Python 接受了它。
foo = {'a': 'b'}
foo.get('a'"")
返回'b'。在 Python 中,'a'"" 在哪里定义为函数的有效参数?
【问题讨论】:
Python 连接所有连续的字符串。无论是在函数中还是在其他地方都没有关系。
参见参考文档的String literal concatenation section:
允许多个相邻的字符串文字(由空格分隔),可能使用不同的引用约定,并且它们的含义与它们的连接相同。
这是在解析级别完成的;最后的字节码只存储一个字符串对象。见What is under the hood of x = 'y' 'z' in Python?
该功能是从 C 复制的。来自 (failed) proposal to remove the feature:
许多 Python 解析规则有意与 C 兼容。[...] 在 C 中,隐式连接是连接字符串的唯一方法,无需使用(运行时)函数调用来存储到变量中。
该功能在生成长字符串时非常有用:
long_value = (
'The quick brown fox jumped over the lazy fox and kept '
'the string within the 80 character boundary.'
)
【讨论】: