在Python中x ='y''z'的含义是什么? [英] What is under the hood of x = 'y' 'z' in Python?

查看:609
本文介绍了在Python中x ='y''z'的含义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在Python中运行 x ='y''z',则会将 x 设置为'yz',这意味着当Python看到彼此相邻的多个字符串时,会发生某种字符串连接。

If you run x = 'y' 'z' in Python, you get x set to 'yz', which means that some kind of string concatenation is occurring when Python sees multiple strings next to each other.

但是,这是什么样的串联?
是实际运行'y'+'z'还是运行''。join('y','z' )还是其他东西?

But what kind of concatenation is this? Is it actually running 'y' + 'z' or is it running ''.join('y','z') or something else?

推荐答案

Python parser 将其解释为一弦。 词法分析文档

The Python parser interprets that as one string. This is well documented in the Lexical Analysis documentation:


字符串文字串联



多个相邻的字符串文字(由空格分隔),可能使用不同的引用约定,是允许的,它们的含义与它们的串联相同。因此, hello'world'等同于 helloworld

已编译的Python代码仅看到一个字符串对象;您可以通过要求Python生成此类字符串的AST来查看此内容:

The compiled Python code sees just the one string object; you can see this by asking Python to produce an AST of such strings:

>>> import ast
>>> ast.dump(ast.parse("'hello' 'world'", mode='eval').body)
"Str(s='helloworld')"

实际上,构建AST的本质是触发连接,因为遍历了语法分析树,请参见 parsestrplus()函数

In fact, it is the very act of building the AST that triggers the concatenation, as the parse tree is traversed, see the parsestrplus() function in the AST C source.

此功能专门用于减少反斜杠的需要;当仍在 logical 内时,使用它可以将物理行上的字符串分解行

The feature is specifically aimed at reducing the need for backslashes; use it to break up a string across physical lines when still within a logical line:

print('Hello world!', 'This string is spans just one '
      'logical line but is broken across multiple physical '
      'source lines.')

多个可以使用括号和方括号隐式连接到一条物理线或花括号。

Multiple physical lines can implicitly be joined into one physical line by using parentheses, square brackets or curly braces.

字符串连接功能原为复制自C,但 Guido van Rossum遗憾地将其添加到Python中 。该帖子引发了一个漫长且非常有趣的主题,并为完全删除该功能提供了很多支持。

This string concatenation feature was copied from C, but Guido van Rossum is on record regretting adding it to Python. That post kicked of a long and very interesting thread, with a lot of support for removing the feature altogether.

这篇关于在Python中x ='y''z'的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆