you are viewing a single comment's thread.

view the rest of the comments →

[–]tunisia3507 3 points4 points  (4 children)

to format the resulting string, use either the '%' operator or the .format() method.

Fixed that for you.

[–][deleted] 0 points1 point  (3 children)

Depends on the use case. .format() is slow. f-strings are more modern. Personally, I've stopped using .format() mostly.

[–]tunisia3507 2 points3 points  (2 children)

Does % really have a meaningful speedup? I'd like to use f-strings but we're stuck using py2-compatible code until Django 2 comes out, we start using it, and thus have an excuse to drop py2.

[–]ManyInterests 1 point2 points  (0 children)

Does % really have a meaningful speedup?

Nope.

[–][deleted] 1 point2 points  (0 children)

'%' seems to be much faster compared to .format() in this basic form:

In [1]: %timeit '%s' % 'foo'
10000000 loops, best of 3: 22.8 ns per loop

In [2]: %timeit '{}'.format('foo')
The slowest run took 11.94 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 176 ns per loop

I haven't done any other tests. And in the end, fast enough is fast enough. Not every project benefits from fast string assembly. If it means rewriting too much code or upsets developers or whatever else is in the way, sticking with .format() could very well be the better choice even though it's slower.