python - 为什么这不抛出 SyntaxError 而不是默默地解释错误?

标签 python

这两个字符串之间应该有一个逗号

foo = ['dumb'
'error']

但是如果您忘记了逗号,它只会将字符串合并在一起而不是产生语法错误。你的结果将是

['dumberror']

我花了几个小时来追踪它。为什么 Python 解释器要合并这些字符串?

最佳答案

这是一个记录在案的功能,允许在源代码中使用字符串文字进行更好的格式化。

Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings.

Source

同样值得注意的是:

Note that this feature is defined at the syntactical level, but implemented at compile time. The ‘+’ operator must be used to concatenate string expressions at run time. Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings).

关于python - 为什么这不抛出 SyntaxError 而不是默默地解释错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10000999/

相关文章:

python - 如何仅从 Python 列表中获取不是字符串的元素?

python - 在 value_counts() 之后从分类中提取索引作为数组

Python 为属性文件中的特定键设置值

python - 如何将功能添加到一起?

python - 在 django 页面中允许 'fuzzy' 翻译?

python - python中具有抽象方法的委托(delegate)设计模式

python - Numba @jit 无法优化简单函数

python - 在 Django 管理命令中添加虚假换行符

python - 检查字典 : exceptions or set? 中的成员资格

python - 如何将handle_unknown ='ignore'传递给sklearn训练好的one hot编码器?