Why is the result two a's followed by four spaces?

a = ‘%(keyname)-6.2s’ % {‘keyname’:‘aaa’}

Actually the result is:

    a= ‘%(keyname)-6.2s’ % {‘keyname’:‘aaa’}
SyntaxError: invalid character '‘' (U+2018)

@yeshuo this is just a weird corner case of old-style formatting. If you at the table in docs for old-style formatting then in the entry for “string” %s formatting, there is a footnote about adding decimal precision:

  1. If precision is N, the output is truncated to N characters.

Without the .2 the output is what you might expect:

In [10]: '%(keyname)-6s' % {'keyname':'aaa'}
Out[10]: 'aaa   '

I somewhat doubt that many people ever intentionally relied on the “string with precision” formatting case. I guess could be useful to truncate long output in an ascii table column.

In case you are wonder about the cryptic comment above, this forum software converts quote characters in normal text to “fancy quotes” which are not valid Python code. To keep things clear, and avoid problems like that one, always provide your code snippets using the code-formatting options of this forum.


Thank you.