Python String Format Method Notes
Python String Format Method Notes
str.format(*args, **kwargs)
(or)
Here p0, p1,... are positional arguments and k0, k1,... are keyword arguments
with values v0, v1,... respectively.
Positional parameters - list of parameters that can be accessed with index of parameter
inside curly braces {index}
Keyword parameters - list of parameters of type key=value, that can be accessed with key
of parameter inside curly braces {key}
The value we wish to put into the placeholders and concatenate with the string
passed as parameters into the format function.
Syntax: { }.format(value)
Parameters :
(value): Can be an integer, floating point numeric constant, string, characters or even
variables.
Return type : Returns a formatted string with the value passed as parameter in the
placeholder position.
Example 1:
print(str.format("Gouthami"))
Multiple pairs of curly braces can be used while formatting the string. Let’s say if another
variable substitution is needed in sentence, can be done by adding a second pair of curly
braces and passing a second value into the method. Python will replace the placeholders by
values in order.
Parameters:
(value1, value2) : Can be integers, floating point numeric constants, strings, characters and
even variables. Only difference is, the number of values passed as parameters in format()
method must be equal to the number of placeholders created in the string.
IndexError: Occurs when string has an extra placeholder and we didn’t pass any value for
it in the format() method. Python usually assigns the placeholders with default index in
order like 0, 1, 2, 3…. to acces the values passed as parameters. So when it encounters a
placeholder whose index doesn’t have any value passed inside as parameter, it throws
IndexError.
When placeholders { } are empty, Python will replace the values passed through str.format()
in order.
The values that exist within the str.format() method are essentially tuple data types and
each individual value contained in the tuple can be called by its index number, which starts
with the index number 0.
These index numbers are placed inside or into the curly braces that serve as the
placeholders in the original string.
print("Modern Web Developer should know {}, {}, {}, {}, {}, {} and
{}".format("HTML","CSS","JavaScript","Git","Framework","JSON","DevOps"))
print("Modern Web Developer should know {0}, {1}, {2}, {3}, {4}, {5} and
{6}".format("HTML","CSS","JavaScript","Git","Framework","JSON","DevOps"))
#Use the index numbers of the values to change the order they appear in the string
print("Modern Web Developer should know {4}, {2}, {5}, {6}, {0}, {1} and
{3}".format("HTML","CSS","JavaScript","Git","Framework","JSON","DevOps"))
More parameters can be included within the curly braces of our syntax. Use the format
code syntax {field_name:conversion}, where field_name specifies the index number of the
argument to the str.format() method, and conversion refers to the conversion code of the
data type.
s – strings
c – character
b – binary
o – octal
e – exponent notation
Syntax:
#Error
#When explicitly converted floating point values to decimal with base10 by 'd'
# type conversion we encounter Value-Error.
print("{:*^20s}".format("Wikis")
How String format() works?
The format() reads the type of arguments passed to it and formats it according to the format
codes defined in the string.
The string "Hello {0}, your balance is {1:9.3f}" is the template string. This contains the
format codes for formatting.
The curly braces are just placeholders for the arguments to be placed. In the above
example, {0} is placeholder for "Goutham" and {1:9.3f} is placeholder for 980.2346.
Since the template string references format() arguments as {0} and {1}, the arguments are
positional arguments. They both can also be referenced without the numbers as {} and
Python internally converts them to numbers.
Internally,
➢ Since "Goutham" is the 0th argument, it is placed in place of {0}. Since, {0} doesn't
contain any other format codes, it doesn't perform any other operations.
➢ However, it is not the case for 1st argument 980.2346. Here, {1:9.3f} places 980.2346 in
its place and performs the operation 9.3f.
➢ “f” specifies the format is dealing with a float number. If not correctly specified, it will
give out an error.
➢ The part before the "." (9) specifies the minimum width/padding the number (980.2346)
can take.
➢ If no alignment option is specified, it is aligned to the right of the remaining spaces. (For
strings, it is aligned to the left.)
➢ The part after the "." (3) truncates the decimal part (2346) upto the given number. In
this case, 2346 is truncated after 3 places.Remaining numbers (46) is rounded off
outputting 235.
For keyword arguments:
Here, instead of just the parameters, we've used a key-value for the parameters. Namely,
ename='Goutham' and salary=980.2346.
Since, these parameters are referenced by their keys as {ename} and {salary:9.3f}, they are
known as keyword or named arguments.
Internally,
The placeholder {ename} is replaced by the value of ename = "Goutham". Since, it doesn't
contain any other format codes, "Goutham" is placed.
For the argument salary=980.2346, the placeholder {salary:9.3f} is replaced by the value
980.2346. But before replacing it, like previous example, it performs 9.3f operation on it.
This outputs 980.235. The decimal part is truncated after 3 places and remaining digits
are rounded off. Likewise, the total width is assigned 9 leaving two spaces to the left.
# default arguments
# positional arguments
# keyword arguments
# mixed arguments
Type Meaning
d Decimal integer
b Binary format
o Octal format
separator
precision: 6)
# integer arguments
# float arguments
print("{:5d}".format(12))
print("{:2d}".format(1234))
print("{:8.3f}".format(12.2346))
print("{:05d}".format(12))
print("{:08.3f}".format(12.2346))
12
1234
12.235
00012
0012.235
In the first statement, {:5d} takes an integer argument and assigns a minimum width of 5.
Since, no alignment is specified, it is aligned to the right.
In the second statement, you can see the width (2) is less than the number (1234), so it
doesn't take any space to the left but also doesn't truncate thenumber.
Unlike integers, floats has both integer and decimal parts. And, the mininum width defined
to the number is for both parts as a whole including ".".
In the third statement, {:8.3f} truncates the decimal part into 3 places rounding off the last
2 digits. And, the number, now 12.235, takes a width of 8 as a whole leaving 2 places to the
left.
If you want to fill the remaining places with zero, placing a zero before the format specifier
does this. It works both for integers and floats: {:05d} and {:08.3f}.
template_string = "Age={0:5d}Salary={1:8.2f}"
print(template_string.format(36,76425.869))
+12.230000 -12.230000
12.230000 -12.230000
12.230000 -12.230000
print("{0:c}".format(65))
target = 800
sales = 400
The operators <, ^, > and = are used for alignment when assigned a certain width to the
numbers.
Type Meaning
print("{:5d}".format(12))
print("{:>5d}".format(12))
print("{:^10.3f}".format(12.2346))
print("{:<05d}".format(12))
print("{:=8.3f}".format(-12.2346))
12
12
12.235
12000
- 12.235
Note: Left alignment filled with zeroes for integer numbers can cause problems as the 3rd
example which returns 12000, rather than 12.
String formatting with format()
print("@{:5}@".format("cat"))
print("@{:<5}@".format("cat"))
print("@{:>5}@".format("cat"))
print("@{:^5}@".format("cat"))
print("@{:*^5}@".format("cat"))
cat..
..cat
.cat.
*cat*
print("{:.3}".format("caterpillar"))
print("{:5.3}".format("caterpillar"))
print("{:^5.3}".format("caterpillar"))
print("{:>5.3}".format("caterpillar"))
print("{:!>5.3}".format("caterpillar"))
cat
cat..
.cat.
..cat
!!cat
# format dict
# format dict
print("{0:*>20.5s}".format('unitedstates'))
***************unite
>>> print("{0:0>+9.2f}".format(452.676))
00+452.68
>>> print("{0:0>+9.2f}".format(-452.676))
00-452.68
>>> print("{0:0=+9.2f}".format(-452.676))
-00452.68
print("{0:A=+9.2f}".format(-452.676))
-AA452.68
Arguments as format codes using format()
You can also pass format codes like precision, alignment, fill character as positional or
keyword arguments dynamically.
templatestring = "{:{fill}{align}{width}}"
num = "{:{align}{width}.{precision}f}"
**cat**
*cat*
123.24..
Here,
In the template string, these keyword arguments are not retrieved as normal strings to be
printed but as the actual format codes fill, align and width.
The arguments replaces the corresponding named placeholders and the string 'cat' is
formatted accordingly.
2) Likewise, in the second example, 123.236 is the positional argument and, align, width
and precision are passed to the template string as format codes.
Applications:
Formatters are generally used to Organize Data. Formatters can be seen in their best light
when they are being used to organize a lot of data in a visual way. If we are showing
databases to users, using formatters to increase field size and modify alignment can make
the output more readable.
print()
print()