Best way to transfer print data in python

I went through http://web2py.com/book/default/chapter/02 and found this:

>>> 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 was given that The last notation is more explicit and less error prone, and is to be preferred.

I wonder what the advantage of using the latest notation is. Would it not be an overhead for productivity?

+3
source share
4 answers
>>> print 'number is ' + str(3)
number is 3

This is by far the worst solution and can cause problems if you make a beginner error "Value of obj: " + objwhere objit is not a string or unicode object. For many concatenations it is not readable at all - it looks like something like echo "<p>Hello ".$username."!</p>";in PHP (it can turn out to be arbitrarily ugly).


  

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

  

. . , , , print "Value of obj: %r" % obj. . , gettext- , , .

, , :

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


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

, , texttext, , . - .

, :

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


, . % dict .
+4

.

  • , . . . .

  • - -, , . .

  • : . . , .

. :

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

"+" - .

"%" - .

, . , , . , , .

[: , web2py, ]

, , .

  • - ,

  • , . .

  • , , .. . .

+2

, .

Hm, , .

?

, .

0

, .

, DRY , , :

  • , . , logging, web2py gettext.
  • .
  • .

, , foo : "%(foo)s" % dict(foo=foo). . , , .

The second method is the easiest method, and this is what you usually use in most programs. This is best used when the format string is immediate, for example. 'values: %s %s %s' % (a, b, c)instead of taking from a variable, for example. fmt % (a, b, c).

The first concatenation is almost never useful, except, perhaps, if you create a list in cycles:

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

however, in this case, it is generally better and faster to use str.join ():

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

Source: https://habr.com/ru/post/1771140/


All Articles