Python String format() Method
The format
method formats the specified values and inserts them inside the string's placeholder. The format
method requires comma delimited parameters specifying the placeholder name and the placeholder's value.
Syntax
Python
Copy Code
string.format(value1, value2,...)
Parameters
Parameter | Description |
---|---|
values... |
Required. The set of objects to format as a string. You can include as many objects as you need and they can be of any type. |
Example
Python
Copy Code
price = 49 txt = "Sale price: ${salePrice:.2f}! That's a {discount:.0%} savings!" print(txt.format(salePrice = price, discount = .5))
Output
Sale price: $49.00! That's a 50% savings!
Notes
Compare the formatting a string with the "f" prefix:
Example
Python
Copy Code
print(f'Sale price: ${price:.2f}! Savings: {.5:.0%}')
Output
Sale price: $49.00! Savings: 50%
Format placeholders
There are also several options for formatting placeholders:
:<
Left aligns the result:>
Right aligns the result:^
Centers the result:=
Places the sign to the left-most position:+
Use a plus sign to indicate if the result is positive or negative:-
Use a minus sign or negative values only:
Use a space to insert an extra space before positive numbers, and a minus sign before negative numbers:,
Use a comma as a thousand's separator:_
Use an underscore as a thousand's separator:b
Binary format:c
Converts the value into the corresponding Unicode character:d
Decimal format:e
Scientific notation with a lowercase e for the exponent:E
Scientific notation with an uppercase E for the exponent:f
Fix point number format:F
Fix point number format and show "inf" (infinity) and "nan" (not a number) as INF and NAN:g
General format:o
Octal format:x
Hex format, lowercase:X
Hex format, uppercase:n
Number format:%
Percent format
Example regarding the + and - format options:
Python
Copy Code
print('{a:+}, {b:+}, {a:-}, {b:-}'.format(a=1, b=-1))
Output
+1, -1, 1, -1