String Formatting Exercise
String Formatting Exercise
Goal
In this exercise we will reinforce the important concepts of string formatting
Procedure
Create a new file called strformat_lab.py .
When the empty script is available and runnable, complete the following four tasks.
Task One
• Write a format string that will take the following four element tuple:
and produce:
1. The first element is used to generate a filename that can help with file sorting. The idea
behind the “file_002” is that if you have a bunch of files that you want to name with
numbers that can be sorted, you need to “pad” the numbers with zeros to get the right
sort order.
That works!
2. The second element is a floating point number. You should display it with 2 decimal
places shown.
3. The third value is an integer, but could be any number. You should display it in
scientific notation, with 2 decimal places shown.
4. The fourth value is a float with a lot of digits – display it in scientific notation with 3
significant figures.
Task Two
Using your results from Task One, repeat the exercise, but this time using an alternate
type of format string (hint: think about alternative ways to use .format() (keywords
anyone?), and also consider f-strings if you’ve not used them already).
Task Three
f-strings are new to Python (version 3.6), but are very powerful and efficient. This means
they are worth understanding and using. And this is made easier than it might be because
they use the same, familiar formatting language that is conventionally used in Python (in
.format()).
Here’s the simplest example, to show how you can use available variables in a f-string:
In addition to referencing variables in the local scope, f-strings can evaluate simple
expressions in line like so:
or
In [8]: a = 5
In [9]: b = 10
• Here’s a task for you: Given the following four element list:
• Now see if you can change the f-string so that it displays the names of the fruit in upper
case, and the weight 20% higher (that is 1.2 times higher).
Often it’s convenient to display data in columns. String formatting helps to make this
straightforward.
In this simple example everything aligns nicely. But that will not be the case when the
numbers to the left of the decimal place vary. Then you will need to use alignment
specifiers. Do some research on this using the links below. Then:
• Write some Python code to print a table of several rows, each with a name, an age and
a cost. Make sure some of the costs are in the hundreds and thousands to test your
alignment specifiers.
• And for an extra task, given a tuple with 10 consecutive numbers, can you work how to
quickly print the tuple in columns that are 5 characters wide? It can be done on one
short line!
https://docs.python.org/3/library/string.html#format-string-syntax