String formatting: Part 1
Contents
String formatting: Part 1#
Table of Contents
We often want to display text to the end user in a specific way. For example,
we may want to display 25.375
as $25.38
if it represents an amount of money
but as 25%
if it represents a percentage.
Python provides a number of tools for this, but for this lesson we’ll focus on
the built in format()
function, which takes two arguments: the value
, and the
formatting string
.
The formatting string is a combination of specific letters or characters that controls the format. This is a mini-language with its own syntax, but this lesson will focus on a few of the most commonly used.
Here’s how you would use the format()
method to print the aforementioned
examples. Don’t worry, this is just a teaser–I don’t expect you to understand
this yet.
print(format(25.375, '.2f'))
print(format(25.375/100, '.0%'))
25.38
25%
Presentation#
At the core of a formatting strings is its presentation. Each letter corresponds to a specific input value type and output presentation. The most common are:
Letter |
Type |
Presentation |
Example |
---|---|---|---|
|
|
string |
|
|
|
decimal |
|
|
|
float |
|
|
|
percent |
|
So here’s a simple example that formats an int
value with a decimal
presentation style.
format(5, "f")
'5.000000'
If there is no presentation type letter in a formatting string, the default is
d
for numbers or s
otherwise.
So technically, these are equivalent.
format("hello", "")
format("hello", "s")
'hello'
format(5, "")
format(5, "d")
'5'
Precision#
Precision goes before the presentation, with the syntax:
.NUMBER
The NUMBER
controls how many digits to display after the decimal point for
floating point numbers.
format(2.5, '.2f')
'2.50'
Or the maximum number of characters to show for strings.
format("Monday", ".3s")
'Mon'
Alignment#
The formatting string for alignment goes before precision and consists of at least two parts:
ALIGNMENT WIDTH
With one of these characters for alignment.
Character |
Alignment |
---|---|
|
right |
|
left |
|
center |
|
align numeric signs |
For example, to center a string to a width of 20
:
format("hello", "^20")
' hello '
It works the same way for numbers.
format(22, ">5d")
' 22'
But you’ll most likely want to use the special number alignment character =
,
which ensures that signs are aligned.
print(format(">", ">5s"), format("=", ">5s"), "\n")
for x in (25, -436, 8, 150, -32, 10):
print(format(x, ">5d"), format(x, "=5d"), sep=" ")
> =
25 25
-436 - 436
8 8
150 150
-32 - 32
10 10
It is important to keep in mind that the width is the number of total characters in the output string, including any signs or decimal points.
By the way, if we break down that last formatting string: "=8.2f"
.
Formatting string |
Refers to |
Meaning |
---|---|---|
|
alignment |
numeric alignment, total width: |
|
precision |
|
|
presentation |
float |
Fill#
There is one more optional part of alignment, the character to fill in any extra space with. By default, the fill character is a space.
The following two examples are the same.
format("hello", "^20")
' hello '
format("hello", " ^20")
' hello '
However, we can use any character for the fill character. Lets say instead we
use the character "="
.
format("hello", "=^20")
'=======hello========'
This is an easy way to make lots of stylish looking headers.
format("hello", "_<20")
'hello_______________'
format("hello", ".>20")
'...............hello'
Note, if you want space between your fill character and the text, add them in the text itself rather than the formatting spec.
format(" hello ", "=^20")
'====== hello ======='
format("hello ", "_<20")
'hello ______________'
format(" hello", ".>20")
'.............. hello'
A fill character is also used to zero-pad numbers:
format(2, "0>2d")
'02'
format(5.2, "0>5.2f")
'05.20'
Exercises#
(String Formatting)
Use the format()
function to:
Format the number
48.7052
to two decimal points.Format the number
2.5
to two decimal points.Format
.25
to25%
Truncate the string
"September"
to a width of3
charactersCenter the string
"Game Over"
to a width of80
Right align the text
"8 of 10"
to a width of80
Left align the string
"Question"
with a fill character of"="
to a width of30
characters.
Solution to Exercise 36 (String Formatting)
>>> format(48.7052, ".2f") # 1
'48.71'
>>> format(2.5, ".2f") # 2
'2.50'
>>> format(.25, ".0%") # 3
'25%'
>>> format("September", ".3s") # 4
'Sep'
>>> format("Game Over", "^80") # 5
' Game Over '
>>> format("8 of 10", ">80") # 6
' 8 of 10'
>>> format("Question ", "=<30") # 7
'Question ====================='
(Align Numbers)
Copy the following function rand_nums()
then call it to generate a list of
10
positive and negative numbers, both floats and ints.
Print the list so that the decimal points and -
signs line up.
Show rand_nums()
code
1from random import randint
2
3def rand_nums(amount=10, ceil=500):
4 """Return a list of random positive and negative ints and floats"""
5 numbers = []
6 for _ in range(amount):
7 # get a random float
8 num = randint(-ceil, ceil) + (1 / randint(1, 99))
9
10 # randomly make it an int
11 if randint(0, 1):
12 num = int(num)
13
14 numbers.append(num)
15
16 return numbers
Need help?
Paste the above
rand_nums()
function into your file.Call it and assign the retuned value to the variable
numbers
.Use a
for
loop to iterate overnumbers
with the variable namenum
.
In each iteration:Use the
format()
function to formatnum
with the format string indicating:float
presentation2
decimal places percisionnumeric sign alignment
width of
7
characters
print the returned value
Example output:
-471.00
434.00
-421.00
-459.99
-399.98
371.07
200.02
29.00
32.00
315.00
Solution to Exercise 37 (Align Numbers)
1numbers = rand_nums()
2
3for num in numbers:
4 print(format(num, "=7.2f"))
Reference#
Presentations#
Letter |
Type |
Presentation |
Details |
Example (Input) |
(Output) |
---|---|---|---|---|---|
|
|
string |
|
|
|
|
|
decimal |
|
|
|
|
|
decimal |
with number superiors |
|
|
|
|
float |
|
|
|
|
|
percent |
|
|
|
|
|
float |
scientific notation 2 |
|
|
|
|
float |
normal or scientific depending on size 2 |
1000000 |
"1e+06" |
|
|
decimal |
binary |
|
|
|
|
decimal |
octal |
|
|
|
|
decimal |
hex 2 |
|
|
|
|
string |
single character |
|
|
See also#
See also