Please write the follwing Python program. Also, show all outputs. String Formatt
ID: 3785052 • Letter: P
Question
Please write the follwing Python program. Also, show all outputs.
String Formatting Lab¶
Building up strings¶
For reference:
The official reference docs:
https://docs.python.org/3/library/string.html#string-formatting
And a more human-readable intro:
https://pyformat.info/
And a nice “Cookbook”:
https://mkaz.tech/python-string-format.html
A Couple Exercises¶
Write a format string that will take:
( 2, 123.4567, 10000)
and produce:
'file_002 : 123.46, 1.00e+04'
Note: 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.
For example:
That is probably not what you want. However:
That works!
So you want to find a string formatting operator that will “pad” the number with zeros for you.
Dynamically Building up format strings¶
Rewrite:
"the 3 numbers are: {:d}, {:d}, {:d}".format(1,2,3)
to take an arbitrary number of values.
Trick: You can pass in a tuple of values to a function with a *:
The idea here is that you may have a tuple of three numbers, but might also have 4 or 5 or....
So you can dynamically build up the format string to accommodate the length of the tuple.
The string object has the format() method, so you can call it with a string that is bound to a name, not just a string literal. For example:
So how would you make an fstring that was the right length for an arbitrary tuple?
Put your code in a function that will return the formatted string like so:
Explanation / Answer
def formatter(tup):
return ("'the {} numbers are : ").format(len(tup)) + (", ".join(["%d"] * len(tup)) + "'") %tup
print(formatter((1,2,3,4,5)))
"""
sample output
'the 5 numbers are : 1, 2, 3, 4, 5'
"""