简体   繁体   English

更好的方法来传递数据在python中打印

[英]better way to pass data to print in python

I was going through http://web2py.com/book/default/chapter/02 and found this: 我正在浏览http://web2py.com/book/default/chapter/02并发现:

>>> print 'number is ' + str(3)
number is 3
>>> print 'number is %s' % (3)
number is 3
>>> print 'number is %(number)s' % dict(number=3)
number is 3

It has been given that The last notation is more explicit and less error prone, and is to be preferred. 已经给出了The last notation is more explicit and less error prone, and is to be preferred.

I am wondering what is the advantage of using the last notation.. will it not have a performance overhead? 我想知道使用最后一种表示法有什么好处..它不会有性能开销吗?

>>> print 'number is ' + str(3)
number is 3

This is definitely the worst solution and might cause you problems if you do the beginner mistake "Value of obj: " + obj where obj is not a string or unicode object. 这绝对是最糟糕的解决方案,如果你做初学者错误"Value of obj: " + obj ,其中obj不是字符串或unicode对象,可能会导致问题。 For many concatenations, it's not readable at all - it's similar to something like echo "<p>Hello ".$username."!</p>"; 对于许多连接,它根本不可读 - 它类似于echo "<p>Hello ".$username."!</p>"; in PHP (this can get arbitrarily ugly). 在PHP(这可以任意丑陋)。


print 'number is %s' % (3) number is 3 print'number is%s'%(3)number is 3

Now that is much better. 现在好多了。 Instead of a hard-to-read concatenation, you see the output format immediately. 您可以立即看到输出格式,而不是难以读取的串联。 Coming back to the beginner mistake of outputting values, you can do print "Value of obj: %r" % obj , for example. 回到输出值的初学者错误,你可以print "Value of obj: %r" % obj ,例如。 I personally prefer this in most cases. 在大多数情况下我个人更喜欢这个。 But note that you cannot use it in gettext-translated strings if you have multiple format specifiers because the order might change in other languages. 但请注意,如果您有多个格式说明符,则不能在gettext-translated字符串中使用它,因为顺序可能会在其他语言中更改。

As you forgot to mention it here, you can also use the new string formatting method which is similar: 你忘了在这里提到它,你也可以使用类似的新字符串格式化方法:

>>> "number is {0}".format(3)
'number is 3'


Next, dict lookup: 接下来,dict查找:

 >>> print 'number is %(number)s' % dict(number=3) number is 3 

As said before, gettext-translated strings might change the order of positional format specifiers, so this option is the best when working with translations. 如前所述,gettext-translated字符串可能会更改位置格式说明符的顺序,因此在使用翻译时此选项最佳。 The performance drop should be negligible - if your program is not all about formatting strings. 性能下降应该可以忽略不计 - 如果你的程序不是格式化字符串。

As with the positional formatting, you can also do it in the new style: 与位置格式一样,您也可以使用新样式:

 >>> "number is {number}".format(number=3) 'number is 3' 


It's hard to tell which one to take. 很难分辨哪一个。 I recommend you to use positional arguments with the % notation for simple strings and dict lookup formatting for translated strings. 我建议您使用带有%表示法的位置参数来表示简单字符串,并使用dict查找格式来表示已翻译的字符串。

I can think of a few differences. 我可以想到一些差异。

  1. First to me is cumbersome , if more than one variable is involved. 如果涉及多个变量, 首先对我来说很麻烦 I can not speak of performance penalty on that. 我不能谈论性能上的惩罚。 See additional arguments below. 请参阅下面的其他参数

  2. The second example is positional dependent and it can be easy to change position causing errors. 第二个例子是位置相关的 ,可以很容易地改变位置导致错误。 It also does not tell you anything about the variables. 它也没有告诉你关于变量的任何信息。

  3. The third example, the position of variables is not important. 第三个例子,变量的位置并不重要。 You use a dictionary . 你使用字典 This makes it elegant as it does not rely on positional structuring of variables. 这使它变得优雅,因为它不依赖于变量的位置结构。

See the example below: 请参阅以下示例:

>>> print 'number is %s %s' % (3,4)
number is 3 4
>>> print 'number is %s %s' % (4,3)
number is 4 3
>>> print 'number is %(number)s %(two)s' % dict(number=3, two=4)
number is 3 4
>>> print 'number is %(number)s %(two)s' % dict(two=4, number=3)
number is 3 4
>>> 

Also another part of discussion on this 另外还有一部分讨论

"+" is the string concatenation operator. “+”是字符串连接运算符。

"%" is string formatting. “%”是字符串格式。

In this trivial case, string formatting accomplishes the same result as concatenation. 在这个简单的情况下,字符串格式化实现与连接相同的结果。 Unlike string formatting, string concatenation only works when everything is already a string. 与字符串格式不同,字符串连接仅在所有内容都是字符串时才有效。 So if you miss to convert your variables to string, concatenation will cause error. 因此,如果您错过将变量转换为字符串,则连接将导致错误。

[Edit: My answer was biased towards templating since the question came from web2py where templates are so commonly involved] [编辑:我的回答偏向于模板化,因为问题来自web2py,其中模板通常涉及]

As Ryan says below, the concatenation is faster than formatting. 正如Ryan在下面所说,连接比格式更快。

Suggestion is 建议是

  1. Use the first form - concatenation, if you are concatenating just two strings 如果只连接两个字符串, 请使用第一种形式 - 连接

  2. Use the second form , if there are few variables. 如果变量很少, 请使用第二种形式 You can invariably see the positions and deal with them 你总能看到立场并处理它们

  3. Use the third form when you are doing templating ie formatting a large piece of string with variable data. 在进行模板化时使用第三种形式 ,即使用可变数据格式化大块字符串。 The dictionary form helps in providing meaning to variables inside the large piece of text. 字典表单有助于为大块文本中的变量提供意义。

I am wondering what is the advantage of using the last notation.. 我想知道使用最后一种符号有什么好处..

Hm, as you said, the last notation is really more explicit and actually is less error prone. 嗯,正如你所说,最后一种表示法更加明确 ,实际上不易出错。

will it not have a performance overhead? 它不会有性能开销吗?

It will have little performance overhead, but it's minor if compared with data fetching from DB or network connections. 它的性能开销很小,但与从数据库或网络连接中获取的数据相比,它是次要的。

It's a bad, unjustified piece of advice. 这是一个糟糕的,不合理的建议。

The third method is cumbersome, violates DRY, and error prone , except if: 第三种方法很麻烦,违反DRY,并且容易出错 ,除非:

  1. You are writing a framework which don't have control over the format string. 您正在编写一个无法控制格式字符串的框架。 For example, logging module, web2py , or gettext . 例如, logging模块, web2pygettext
  2. The format string is extremely long. 格式字符串非常长。
  3. The format string is read from a file from a config file. 从配置文件中的文件中读取格式字符串。

The problem with the third method should be obvious when you consider that foo appears three times in this code: "%(foo)s" % dict(foo=foo) . 当您考虑foo在此代码中出现三次时,第三种方法的问题应该是显而易见的: "%(foo)s" % dict(foo=foo) This is error prone. 这很容易出错。 Most programs should not use the third method, unless they know they need to. 除非他们知道需要,否则大多数程序不应使用第三种方法。

The second method is the simplest method, and is what you generally use in most programs. 第二种方法是最简单的方法,也是大多数程序中通常使用的方法。 It is best used when the format string is immediate, eg 'values: %s %s %s' % (a, b, c) instead of taken from a variable, eg fmt % (a, b, c) . 最好在格式字符串是立即时使用,例如'values: %s %s %s' % (a, b, c)而不是从变量中获取,例如fmt % (a, b, c)

The first concatenation is almost never useful, except perhaps if you're building list by loops: 第一个连接几乎从来没用过,除非您正在逐个构建列表:

s = ''
for x in l:
    s += str(x)

however, in that case, it's generally better and faster to use str.join(): 但是,在这种情况下,使用str.join()通常会更好更快:

s = ''.join(str(x) for x in l)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM