MicroPython : Formatting Strings
Contents
Introduction
The MicroPython string formatting capability is quite powerful. The MicroPython format() function closely (but not completely) aligns with the Python language standard.
All examples in this article are original and have been tested on a micro:bit for correctness using the Mu Editor.
The Interpolation (%) Operator
The Interpolation Operator (%) is built-in to operate on string objects and provides simple positional formatting. It is similar to the C language printf() style string formatting. However in the MicroPython world it is now considered old-fashioned.
In the above example the best way to describe the use of the interpolation operator is by example:
Example 1
name = 'Jane'
print('My friend %s is a lawyer' %name)
Output:
My friend Jane is a lawyer
Conversion Type
The ‘s’ from the placeholder %s is known as the conversion type; in this case, string. When the string is printed, the %s placeholder is replaced by the value of the variable name.
The most commonly used conversion types are:
- ‘s’ : string
- ‘d’ : integer
- ‘a.bf’ : floating point decimal
- ‘e’ or ‘E’ : Floating point exponential
- ‘x’ or ‘X’ : hexadecimal
More than one placeholders can be used in the same string. In this case the values are placed in a tuple.
Example 2
name = 'Jane'
age = 42
print('My friend %s is a lawyer. Her age is %d.' %(name, age))
Output:
My friend Jane is a lawyer. Her age is 42.
The floating point decimal conversion type optionally allows specification of the total number of digits displayed (‘a’) and the number of digits displayed to the right of the decimal point (‘b’).
Example 3
pi = 3.141593
print('The value of pi is %s to 6 decimals.' %pi)
print('The value of pi is %5.4f to 4 decimals.' %pi)
print()
BigInt = pow(9,15)
print('The big value is %d.' %BigInt)
print('The big value is %e.' %BigInt)
Output:
The value of pi is 3.141593 to 6 decimals. The value of pi is 3.1416 to 4 decimals. The big value is 205891132094649. The big value is 2.058911e+14.
The format() Function
The format() method formats the specified value(s) and insert them inside the string's placeholder.
The placeholder is defined using curly brackets: {}. The placeholders can be identified using named indexes e.g. {price}, numbered indexes e.g. {0}, or even empty placeholders i.e. {}.
The format() method returns the formatted string.
This is best shown by examples
Example 3
# Demonstrate string format() method
# Define some strings
pet = 'dog'
name = 'Sam'
age = 6
size = 'large'
activity = 'walking'
location = 'the park'
# format() with empty placeholders.
s1 = 'My pet is a {} and his name is {}.'.format(pet, name)
# format() with numbered indexes.
s2 = '{0} is a {1} {2} and is {3} years old.'.format(name, size, pet, age)
# format() with named indexes.
s3 = 'He enjoys {exercise} in {where}.'.format(exercise = activity, where = location)
s4 = 'We go to {where} in the {transport}.'.format(where = location, transport = 'car')
print(s1)
print(s2)
print(s3)
print(s4)
Output:
My pet is a dog and his name is Sam. Sam is a large dog and is 6 years old. He enjoys walking in the park. We go to the park in the car.
Formatting Type
A formatting type can be added inside the placeholder. Some of the more commonly used formatting types are explained in Table 1.
Type | Meaning |
---|---|
:< | Left align 'Counting:{:<8}'.format('1,2,3')
|
:> | Right align 'Counting:{:>8}'.format('1,2,3')
|
:^ | Centre align 'Counting:{:^8}'.format('1,2,3')
|
:+ | Forces a '+' if positive value 'Counting: {:+}, {:+}, {:+}'.format(1,2,3)
|
:, | Use comma as thousands separator 'Big number: {:,}'.format(123456789)
|
:b | binary format '27 in binary = {:b}'.format(27)
|
:X | hexadecimal format '27 in hexadecimal = {:X}'.format(27)
|
:d | Decimal format '0xC00FFEE is {:,d} decimal'.format(0xC00FFEE)
|
:c | ASCII code converted to equivalent character 'ASCII code 69 is "{:c}"'.format(69)
|
:a.bf | Fixed floating point format. Rounding with "a.b" is optional. '15.9684 to 2 decimals:{:.2f}'.format(15.9684)
|
:a.be | Scientific format. Rounding with "a.b" is optional. '151.9 = {:.4e} scientific format'.format(151.9)
|
:.a% | % format. Number of decimals with ".a" is optional. '26/29 = {:.1%}'.format(26/29)
|