Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python rule for parsing integer formatting specifier?

I am trying to understand code that uses the following expression

f"{current_file_start_time.year}{current_file_start_time.month:02}{current_file_start_time.day:02}"

Here is a minimum working example, pasted from a Spyder console:

from datetime import datetime, timezone
current_file_start_time = datetime.now(timezone.utc)
current_file_start_time.month
   Out[20]: 4
type(_)
   Out[21]: int
 f"{current_file_start_time.year}{current_file_start_time.month:02}{current_file_start_time.day:02}"
   Out[22]: '20240410'

More specifically, The month 04 is due to the component {current_file_start_time.month:02}. The relevant rules seem to be described by this reference page:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

format_spec     ::=  [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

The leading 0 in {current_file_start_time.month:02} seem to be matchable to several components of format_spec above, namely: (i) [fill]; (ii) ["0"]; and (iii) and the leading digit of [width]. I can’t find a description of component (ii), perhaps it’s a special case of using "0" for fill.

What are the rules that determine whether 0 in {current_file_start_time.month:02} is used for fill, "0", or the leading digit of width? While it may not matter much in this example, I would like to not guess when composing other format specifiers?

I am using Python 3.9.

>Solution :

Reading further down in the specification:

When no explicit alignment is given, preceding the width field by a zero (‘0’) character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of ‘0’ with an alignment type of ‘=’.

So 02 it represents ["0"][width] in the format spec.

format_spec ::= [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]

It can’t be fill because [[fill]align] means if fill is present, align is also present.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading