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

s

str

string

"hello"

d

int

decimal

"1000"

f

float, int

float

"1.000000"

%

float, int

percent

"20.000000%"

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

=8

alignment

numeric alignment, total width: 8

.2

precision

2 digits after the decimal

f

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#

Exercise 36 (String Formatting)

Use the format() function to:

  1. Format the number 48.7052 to two decimal points.

  2. Format the number 2.5 to two decimal points.

  3. Format .25 to 25%

  4. Truncate the string "September" to a width of 3 characters

  5. Center the string "Game Over" to a width of 80

  6. Right align the text "8 of 10" to a width of 80

  7. Left align the string "Question" with a fill character of "=" to a width of 30 characters.

Exercise 37 (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?
  1. Paste the above rand_nums() function into your file.

  2. Call it and assign the retuned value to the variable numbers.

  3. Use a for loop to iterate over numbers with the variable name num.
    In each iteration:

    • Use the format() function to format num with the format string indicating:

      • float presentation

      • 2 decimal places percision

      • numeric 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

Reference#

Presentations#

Letter

Type

Presentation

Details

Example (Input)

(Output)

s

str

string

"hello"

"hello"

d, i

int

decimal

1

1000

"1000"

n

int

decimal

with number superiors

1000

"1,000"

f

float, int

float

1.0

"1.000000"

%

float, int

percent

0.2

"20.000000%"

e, E

float, int

float

scientific notation 2

1.5

"1.500000e+00"

g, G

float, int

float

normal or scientific depending on size 2

1.5

1000000

"1.5"

"1e+06"

b

int

decimal

binary

25

"1010"

o

int

decimal

octal

10

"12"

x, X

int

decimal

hex 2

10

"a"

c

int

string

single character

65

"A"

See also#


1

alias

2(1,2,3)

case of letter indicates case of output