String Formatting
Strings allow you to hold textual data in Python. Often times, you'll want to print a string and pass in a variable. You can use the format
method on strings to pass in a variable.
A more useful example would be to print grammatically correct English sentences about the data.
In the example below, we want to print the results of the scooter ride data below to easily highlight the data's meaning.
Notice below if we want to pass in several variables, we must provide a numerical counter in the braces {}
.
Basic formatting:
Value conversion:
The new-style simple formatter calls by default the __format__() method of an object for its representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r conversion flags.
In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion.
Setup:
Example-1
Example-2:
Padding and aligning strings:
A value can be padded to a specific length. See the following examples where the value '15' is encoded as part of the format string.
Note: The padding character can be spaces or a specified character.
Example:
Align right:
By argument:
In the previous example, the value '15' is encoded as part of the format string. It is also possible to supply such values as an argument.
Example:
Align center:
Example:
By argument:
Example:
Numbers:
Integers:
Padding numbers:
Similar to strings numbers.
Example-1:
The padding value represents the length of the complete output for floating points. In the following example '{:05.2f}' will display the float using five characters with two digits after the decimal point.
Example-2:
Signed numbers:
By default only negative numbers are prefixed with a sign, but you can display numbers prefixed with the positive sign also.
Example-1:
You can use a space character to indicate that negative numbers (should be prefixed with a minus symbol) and a leading space should be used for positive numbers.
Example-2:
Example-3:
You can control the position of the sign symbol relative to the padding.
Example-4:
Named placeholders:
Both formatting styles support named placeholders. Here is an example:
Example-1:
.format() method can accept keyword arguments.
Example-2:
Datetime:
You can format and print datetime object as per your requirement.
Example:
Last updated