0

I have the following code which uses old style string formatting (this is not a modulo operation)

'b0%04x%02x' % (0, 0x0a)

which results in:

b000000a

Can someone explain what is happening here?

divibisan
  • 11,659
  • 11
  • 40
  • 58
user892960
  • 309
  • 2
  • 11

1 Answers1

1

This is "old stye" string formatting. It replaces each format specifier (starting with % in the string) with a formatted value of an argument in the tuple.

In your example:

fmt string     output    description
-------------------------------------------------------------------------------
b0         -> b0       - not a format specifier, output as literal characters
  %04x     ->   0000   - 4-digit hex representation of the first value in tuple
      %02x ->       0a - 2-digit hex representation of the second value
Mikhail Burshteyn
  • 4,762
  • 14
  • 27
  • I wouldn't say that's the "old style" because it is just another method that Python provides natively to format a string. – Derek 朕會功夫 Sep 06 '18 at 17:01
  • Well, 1) it's the oldest style, 2) it has some unexpected quirks, especially with tuples, and 3) new-style formatting with .format has a bunch of features not available with %-style. Not to mention f-strings. – Mikhail Burshteyn Sep 06 '18 at 17:03
  • I would argue that it is originally the only supported way to natively format a string, but it's definitely not the "old style" because it is included in the latest specification. The term "old" can be misleading because it can imply the syntax is deprecated while it is actually not. – Derek 朕會功夫 Sep 06 '18 at 17:06