在 Python 中使用逗号、连接和字符串格式化程序的区别 [英] Difference between using commas, concatenation, and string formatters in Python

查看:41
本文介绍了在 Python 中使用逗号、连接和字符串格式化程序的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

x = "你好"y = "世界"

使用逗号:

print "I am Printing" , x, y # 我知道使用逗号会自动给出空格

通过使用连接:

print "我正在打印" + " " + x + " " + y

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

print "我正在打印 %s %s" % (x, y)

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

我正在打印Hello World

这三者之间有什么区别,是否有任何特定情况下一个比另一个更受欢迎?

解决方案

首先要回答一般性问题,在编写代码时,通常会使用打印将脚本中的信息输出到屏幕,以确保得到你所期望的.

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

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

1.打印

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

用逗号打印语句 (Python 2)

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

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

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

x = "你好"y = "世界"打印我正在打印",打印 x,打印 y

会输出:

我正在打印Hello World

打印功能

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

from __future__ import print_function

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

<预><代码>>>>打印('你好', '世界', sep='-', end='\n****\n')你好,世界****>>>

默认为 ' ' 为 sep 和 '\n' 为结束:

<预><代码>>>>打印('你好','世界')你好,世界>>>

2.字符串连接

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

print('你好' + '-' + '世界')

将打印

hello-world

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

print('这里是一个数字:' + str(2))

印刷品

这里是一个数字:2

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

<预><代码>>>>print('这里是一个数字:' + 2)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:无法连接str"和int"对象

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

3.字符串插值

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

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

print('我正在打印 {0} 和 {1}'.format(x, y))

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

print('我正在打印 {} 和 {}'.format(x, y))

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

print('我正在打印 {x} 和 {y}'.format(x=x, y=y))

相对于 % 样式格式(此处未演示)的最大好处是它允许您组合位置参数和关键字参数

print('我正在打印 {0} 和 {y}'.format(x, y=y))

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

Python 3.6 将具有 格式文字,具有更优雅的语法(减少冗余).简单的语法类似于:

print(f'我正在打印 {x} 和 {y}')

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

<预><代码>>>>print(f'我正在打印 {"hello".capitalize()} 和 {"Wo" + "rld"}')我正在打印 Hello and World

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:

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?

解决方案

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.

1. Printing

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

Print Statements with Commas (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):

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:

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:

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

2. String Concatenation

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

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).

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):

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 will have format literals, with a more elegant syntax (less redundancy). The simple syntax is something like:

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

这篇关于在 Python 中使用逗号、连接和字符串格式化程序的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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