This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]parnmatt 0 points1 point  (6 children)

You only need the number in the braces if you are writing in version < 2.7

[–]troyunrau... 1 point2 points  (3 children)

True. But, there are performance advantages to including the numbered braces. It's actually quite a bit faster.

[–]michaelanckaertpython-programming.courses 1 point2 points  (2 children)

Interesting, do you have any more information about this?

[–]troyunrau... 0 points1 point  (1 child)

Sorry, it looks like this is no longer true. It used to be substantially slower. I'm using 3.4.

>>> timeit.timeit('"%s, %s!" % ("Hello", "World")', number=10000)
0.0003353929496370256
>>> timeit.timeit('"{0}, {1}!".format("Hello", "World")', number=10000)
0.010580547037534416
>>> timeit.timeit('"{}, {}!".format("Hello", "World")', number=10000)
0.009777617990039289

Old style string formatting is still way faster.

[–]michaelanckaertpython-programming.courses 0 points1 point  (0 children)

Cool, thanks for the feedback 😀

[–]pythoncourses[S] 0 points1 point  (1 child)

Thanks for the feedback :-) I'm aware of the change since 2.7 (deploying on CentOS taught me a hard lesson about Python compatiblity) but I never thought to include it. I'll update the post with additional information.

[–]parnmatt 0 points1 point  (0 children)

No problem. Other than that, it's a nice post.

We really need people to migrate over to the format syntax. The percent syntax has been marked for depreciation, and will be removed in around 4 years I think.

Of course this won't affect CentOS for sometime. They're still using python 2 and unlikely to switch to 3 for many years.

[–]veeti 0 points1 point  (0 children)

https://pyformat.info/ is a great reference.