在 Python 中使用逗号、连接和字符串格式化程序的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21542694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:06:46  来源:igfitidea点击:

Difference between using commas, concatenation, and string formatters in Python

pythonstring

提问by Pooja

I am learning python(2.7) on my own. I have learned that we can use the following ways to put strings and variables together in printing:

我正在自己学习 python(2.7)。我了解到我们可以使用以下方法将字符串和变量放在一起打印:

x = "Hello"
y = "World"

By using commas:

通过使用逗号:

print "I am printing" , x, y  # I know that using comma gives automatic space

By using concatenation :

通过使用串联:

print "I am printing" + " " + x + " " + y 

By using string formatters

通过使用字符串格式化程序

print "I am printing %s %s" % (x, y) 

In this case all three print the same:

在这种情况下,所有三个打印相同:

I am printing Hello World

What is the difference between the three and are there any particular instances where one is preferred over the other?

三者之间有什么区别,是否有任何特定情况下一个优先于另一个?

采纳答案by Aaron Hall

To answer the general question first, you would use printing in general to output information in your scripts to the screen when you're writing code to ensure that you're getting what you expect.

要首先回答一般问题,在编写代码时,通常会使用打印将脚本中的信息输出到屏幕上,以确保获得预期的结果。

As your code becomes more sophisticated, you may find that logging would be better than printing, but that's information for another answer.

随着您的代码变得更加复杂,您可能会发现日志记录比打印更好,但这是另一个答案的信息。

There is a big difference between printing and the return values' representations that are echoed in an interactive session with the Python interpreter. Printing should print to your standard output. The echoed representation of the expression's return value (that show up in your Python shell if not None) will be silent when running the equivalent code in scripts.

在与 Python 解释器的交互式会话中回显的打印和返回值的表示之间存在很大差异。打印应该打印到您的标准输出。None在脚本中运行等效代码时,表达式返回值的回显表示(如果没有,则显示在您的 Python shell 中)将是静默的。

1. Printing

1. 印刷

In Python 2, we had print statements. In Python 3, we get a print function, which we can also use in Python 2.

在 Python 2 中,我们有打印语句。在 Python 3 中,我们有一个打印函数,我们也可以在 Python 2 中使用它。

Print Statements with Commas (Python 2)

用逗号打印语句 (Python 2)

The print statement with commas separating items, uses a space to separate them. A trailing comma will cause another space to be appended. No trailing comma will append a newline character to be appended to your printed item.

用逗号分隔项目的打印语句使用空格来分隔它们。尾随逗号将导致附加另一个空格。没有尾随逗号会附加换行符以附加到您的打印项目。

You could put each item on a separate print statement and use a comma after each and they would print the same, on the same line.

您可以将每个项目放在单独的打印语句中,并在每个项目后使用逗号,它们将在同一行上打印相同的内容。

For example (this would only work in a script, in an interactive shell, you'd get a new prompt after every line):

例如(这仅适用于脚本,在交互式 shell 中,您会在每一行后得到一个新提示):

x = "Hello"
y = "World"

print "I am printing",
print x,
print y 

Would output:

会输出:

I am printing Hello World

Print Function

打印功能

With the built-in print function from Python 3, also available in Python 2.6 and 2.7 with this import:

使用 Python 3 中的内置打印函数,在 Python 2.6 和 2.7 中也可以使用此导入:

from __future__ import print_function

you can declare a separator and an end, which gives us a lot more flexibility:

你可以声明一个分隔符和一个结尾,这给了我们更多的灵活性:

>>> print('hello', 'world', sep='-', end='\n****\n')
hello-world
****
>>>

The defaults are ' 'for sep and '\n'for end:

默认值是' 'sep 和'\n'end:

>>> print('hello', 'world')
hello world
>>> 

2. String Concatenation

2. 字符串连接

Concatenation creates each string in memory, and then combines them together at their ends in a new string (so this may not be very memory friendly), and then prints them to your output at the same time. This is good when you need to join strings, likely constructed elsewhere, together.

串联在内存中创建每个字符串,然后在它们的末端将它们组合在一起形成一个新字符串(因此这可能不是非常适合内存使用),然后同时将它们打印到您的输出中。当您需要将可能在其他地方构造的字符串连接在一起时,这很好。

print('hello' + '-' + 'world')

will print

将打印

hello-world

Be careful before you attempt to join in this manner literals of other types to strings, to convert the literals to strings first.

在尝试以这种方式将其他类型的文字连接到字符串之前要小心,首先将文字转换为字符串。

print('here is a number: ' + str(2))

prints

印刷

here is a number: 2

If you attempt to concatenate the integer without coercing it to a string first:

如果您尝试连接整数而不先将其强制为字符串:

>>> print('here is a number: ' + 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

This should demonstrate that you should only ever attempt to concatenate variables that are known to be strings. The new way of formatting demonstrated next handles this issue for you.

这应该表明您应该只尝试连接已知为字符串的变量。接下来演示的新格式设置为您解决了这个问题。

3. String Interpolation

3. 字符串插值

The formatting you're demonstrating is the old style of string interpolation, borrowed from C. It takes the old string and one time creates a new one. What it does is fairly straightforward. You should use this when you may seem likely to building up a fairly large template (at 3+ lines and 3+ variables, you definitely should be doing it this way).

您正在演示的格式是从 C 中借用的旧字符串插值样式。它使用旧字符串并一次创建一个新字符串。它所做的相当简单。当您似乎有可能构建一个相当大的模板时,您应该使用它(在 3+ 行和 3+ 变量处,您绝对应该这样做)。

The new way of doing that would be to do this (using the index of the arguments):

这样做的新方法是这样做(使用参数的索引):

print('I am printing {0} and {1}'.format(x, y))

or in python 2.7 or 3 (using the implied index):

或在 python 2.7 或 3 中(使用隐含索引):

print('I am printing {} and {}'.format(x, y))

or with named arguments (this is semantically easy to read, but the code doesn't look very DRY (i.e. Don't Repeat Yourself))

或使用命名参数(这在语义上易于阅读,但代码看起来不太干(即不要重复自己))

print('I am printing {x} and {y}'.format(x=x, y=y))

The biggest benefit of this over %style formatting (not demonstrated here) is that it lets you combine positional and keyword arguments

%样式格式相比(此处未演示)的最大好处是它可以让您组合位置参数和关键字参数

print('I am printing {0} and {y}'.format(x, y=y))

New in Python 3.6, format literals

Python 3.6 中的新功能,格式化文字

Python 3.6 will have format literals, with a more elegant syntax (less redundancy). The simple syntax is something like:

Python 3.6 将具有格式文字,具有更优雅的语法(更少的冗余)。简单的语法是这样的:

print(f'I am printing {x} and {y}')

The format literals can actually execute code in-place:

格式文字实际上可以就地执行代码:

>>> print(f'I am printing {"hello".capitalize()} and {"Wo" + "rld"}')
I am printing Hello and World

回答by dana gradstein

you should build list and use join with delimiter for example ",".join(list_name)

您应该构建列表并使用带有分隔符的连接,例如“,”.join(list_name)