In the reading of Python's Format Specification Mini-Language,
format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::= <any character> align ::= "<" | ">" | "=" | "^" sign ::= "+" | "-" | " " width ::= integer precision ::= integer type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
the grammar really confused me.
For example, if I want to convert int to binary representation I can do this
"{0:b}".format(100) "{:b}".format(100) # but this is fine too, so what dose the 0 do?
I know that b
represent the type
part in the specification, but I can't figure out the role for 0
and :
, what are they doing?
The colon character (' : ') essentially tells Pandas that we want to retrieve all columns. Remember from the syntax explanation above that we can use two integer index values inside of iloc[] . The first is the row index and the second is the column index.
[::1] means: Start at the beginning, end when it ends, walk in steps of 1 (which is the default, so you don't even need to write it). [::-1] means: Start at the end (the minus does that for you), end when nothing's left and walk backwards by 1. 10th June 2019, 1:34 PM.
In the esoteric programming language INTERCAL, the colon is called "two-spot" and is used to identify a 32-bit variable—distinct from a spot (.) which identifies a 16-bit variable.
String formatting is the process of infusing things in the string dynamically and presenting the string. There are four different ways to perform string formatting:- Formatting with % Operator. Formatting with format() string method. Formatting with string literals, called f-strings.
You are only looking at the grammar for the format_spec
, the full grammar is specified higher up on the same page:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}" field_name ::= arg_name ("." attribute_name | "[" element_index "]")* arg_name ::= [identifier | integer] attribute_name ::= identifier element_index ::= integer | index_string index_string ::= <any source character except "]"> + conversion ::= "r" | "s" format_spec ::= <described in the next section>
In the replacement_field
syntax notice the :
preceding the format_spec
.
The
field_name
is optionally followed by a conversion field, which is preceded by an exclamation point'!'
, and aformat_spec
, which is preceded by a colon':'
When the field_name
and/or conversion
are specified, :
marks the end of former and the start of the format_spec
.
In your example,
>>> "{0:b}".format(100) '1100100'
zero specifies the optional field_name
which in this case corresponds to the index of the item to be formatted in the passed parameter tuple; it is optional so it can be dropped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With