Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
867 views
in Technique[技术] by (71.8m points)

string - What is under the hood of x = 'y' 'z' in 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

String literal concatenation

Multiple adjacent string 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".

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')"

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...