python tutorial - Formatting dictionary strings - learn python - python programming
- Targets on the left can refer to the keys in a dictionary on the right so that they can fetch the corresponding values.
- In the example below, the (m) and (w) in the format string refers to the keys in the dictionary on the right and fetch their corresponding values.
- We can build a dictionary of values and substitute them all at once with a single formatting expression that uses key-based references. This technique can be used to generate text:
- As an another example, we can use it for build-in function, vars():
String formatting by method calls
- Unlike formatting using expressions which is based on C's printf, string formatting using method calls is regarded as more Python-specific.
Template basics
- This new string object's format method uses the subject string as a template and takes any number of arguments that represent values to the substituted according to the template.
- Within the subject string, curly braces designate substitution targets and arguments to be inserted either by position such as {1} or keyword such as language.
- Arbitrary object type can be substituted from a temporary string:
Formatting with keys and attributes
- Format strings can name object attributes and dictionary keys.
- Square brackets name dictionary keys and dots denote object attributes of an item referenced by position or keyword.
- In the example above, the first one indexes a dictionary on the key Machine and then fetches the attribute platform from the imported sys module.
- Though the 2nd case in the example is doing the same thing, but names the objects by keyword not by its position.
Working with specific formatting
- By adding extra syntax in the format string, we can achieve more specific layouts similar to the % expressions.
- For the formatting method, we can use a colon after the substitution target's identification, followed by a format specifier that can name the field size, justification, and a specific type code.
- fieldName is a number or keyword naming an argument, followed by optional .name attribute or [index] references.
- conversionFlag can be r, s, or a to call repr, str, or ascii built-in functions on the value, respectively.
- formatSpecification specifies how the value should be presented.
- The alignment for the formatSpecification can be <. >, =, or ^, for left alignment, right alignment, padding after a sign character, or centered alignment, respectively.
- The following example shows the specification for floating point numbers:
- The following example is for the review of formatting we've discussed so far:
- After importing the module, we get the following output from the interactive shell:
- The first specification {0:.1f} is for the sz and the second one {1[0]} is for the 'KB' in UNITS list.