The most efficient way to print strings in Python?

Thus, according to optimization tips at http://wiki.python.org/moin/PythonSpeed/PerformanceTips , string concatenation should be done using

out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals()
and not
out = "<html>" + head + prologue + query + tail + "</html>" My question: is it the same if I wanted to print, and not store the value? Also, will running sequential print statements on the same line be faster? How would it be better to use

print "Some word"
print "Another line"
print "something else"

or

print '''Some word
Another line
something else'''

Thanks in advance!

+3
source share
3 answers

, , format , , . .


: ,

. , - , , . ( ) , , . , , , + , + + ..

, , . , Python . , @gnibbler , , .

Python - "".join(...). . , StringIO:

>>> from io import StringIO
>>> foo = StringIO()
>>> for letter in map(chr, range(128)):
...     foo.write(letter)
...
>>> foo.seek(0)
0
>>> foo.read()
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\
x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC
DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'
+5

( ) , . . PyString_ConcatAndDel stringobject.c

, ,

, . , id()

>>> s = ""
>>> prev_id = None
>>> for i in range(1000):
...  s += "*"
...  if prev_id != id(s):
...   print id(s), len(s)
...   prev_id = id(s)
... 
3077352864 1
3077437728 2
3077434328 9
3077428384 17
3077379928 25
3077291808 33
3077712448 41
3077358800 49
3077394728 57
3077667680 65
3077515120 73
3077354176 81
3077576488 89
3077559200 97
3077414248 105
3077670336 113
3077612160 121
3077707040 129
3077526040 137
3077571472 145
3077694944 153
3077595936 161
3077661904 169
3077552608 177
3077715680 185
3077583776 193
3077244304 201
3077604560 209
3077510392 217
3077334304 225
144468768 233
144787416 245
144890104 389
+6

There is no need to concatenate for printing:

print "<html>", head, prologue, query, tail, "</html>"

This works the same way (a comma at the end prevents it \n):

print "<html>",
print head,
...
print "</html>"

I think the answer is NO, not print-only concatenation, it will make things slower. But you really should not put up with this, just write some tests and a profile using timeit .

+2
source

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


All Articles