编程语言
首页 > 编程语言> > Python字符串文字串联

Python字符串文字串联

作者:互联网

我可以使用以下语法创建多行字符串:

string = str("Some chars "
         "Some more chars")

这将产生以下字符串:

"Some chars Some more chars"

Python是加入这两个单独的字符串还是编辑器/编译器将它们视为单个字符串?

P.s:我只是想了解内部情况.我知道还有其他方法来声明或创建多行字符串.

解决方法:

阅读reference manual,就在那里.
特别:

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,

(强调我的)

这就是为什么:

string = str("Some chars "
         "Some more chars")

与str完全相同:str(“some chars some some chars”).

此操作在字符串文字可能出现的任何地方执行,列出initiliazations,函数调用(如上面的str的情况)等等.

唯一需要注意的是当一个字符串文字不包含在grouping delimiters (), {} or []中的一个之间,而是在两个单独的physical lines之间传播.在这种情况下,我们可以选择use反斜杠字符来连接这些行并得到相同的结果:

string = "Some chars " \
         "Some more chars"

当然,在同一物理行上串联字符串不需要反斜杠. (string =“你好”“世界”就好了)

Is Python joining these two separate strings or is the editor/compiler treating them as a single string?

Python是,现在,当Python正是这样做时,这就是事情变得有趣的地方.

从我可以收集到的东西(用一小撮盐,我不是解析专家),当Python将给定表达式的解析树(LL(1) Parser)转换为相应的AST(Abstract Syntax Tree)时,就会发生这种情况.

您可以通过parser模块获取已解析树的视图:

import parser

expr = """
       str("Hello "
           "World")
"""
pexpr = parser.expr(expr)
parser.st2list(pexpr)

这会转储一个非常大且令人困惑的列表,它表示从expr中的表达式解析的具体语法树:

-- rest snipped for brevity --

          [322,
             [323,
                [3, '"hello"'],
                [3, '"world"']]]]]]]]]]]]]]]]]],

-- rest snipped for brevity --

这些数字对应于解析树中的符号或标记,从符号到语法规则和令牌到常量的映射分别在Lib/symbol.pyLib/token.py中.

正如您在我添加的剪切版本中所看到的,您有两个不同的条目对应于解析的表达式中的两个不同的str文字.

接下来,我们可以通过标准库中提供的ast模块查看前一个表达式生成的AST树的输出:

p = ast.parse(expr)
ast.dump(p)

# this prints out the following:
"Module(body = [Expr(value = Call(func = Name(id = 'str', ctx = Load()), args = [Str(s = 'hello world')], keywords = []))])"

在这种情况下,输出更加用户友好;你可以看到函数调用的args是单个连接字符串Hello World.

此外,我还偶然发现了一个很酷的module,它为ast节点生成树的可视化.使用它,表达式expr的输出可视化如下:

expression tree for the given expression

图像被裁剪以仅显示表达式的相关部分.

如您所见,在终端叶节点中,我们有一个str对象,即“Hello”和“World”的连接字符串,即“Hello World”.

如果您有足够的勇气,请深入了解源代码,将表达式转换为解析树的源代码位于Parser/pgen.c,而将解析树转换为抽象语法树的代码位于Python/ast.c.

此信息适用于Python 3.5,我非常确定,除非您使用的是某些非常旧的版本(< 2.5),否则功能和位置应该相似. 另外,如果你对python的整个编译步骤感兴趣,那么核心贡献者之一Brett Cannon将在视频From Source to Code: How CPython’s Compiler Works中提供一个很好的温和介绍.

标签:python,string,python-2-7,python-internals
来源: https://codeday.me/bug/20190927/1824507.html