String Formatting in Python Flashcards
Give an example of using zero-based positional arguments to the .format() method.
The string to print is as follows
6 bananas cost $1.74
When using the .format() method use the following values in the arguments
6
bananas
1.74
print(‘{0} {1} cost ${2}’.format(6, ‘bananas’, 1.74))
6 bananas cost $1.74
In this example, is the string ‘{0} {1} cost ${2}’. The replacement fields are {0}, {1}, and {2}, which contain numbers that correspond to the zero-based positional arguments 6, ‘bananas’, and 1.74. Each positional argument is inserted into the template in place of its corresponding replacement field:
Give an example of using keyword arguments to the .format() method.
The string to print is as follows
6 bananas cost $1.74
When using the .format() method use the following values in the arguments
6
bananas
1.74
print(‘{quantity} {item} cost ${price}’.format(
quantity=6,
item=’bananas’,
price=1.74))
6 bananas cost $1.74
In this case, the replacement fields are {quantity}, {item}, and {price}. These fields specify keywords that correspond to the keyword arguments quantity=6, item=’bananas’, and price=1.74. Each keyword value is inserted into the template in place of its corresponding replacement field
Keyword arguments are inserted into the template string in place of keyword replacement fields with the same name:
‘{x}/{y}/{z}’.format(x=’foo’, y=’bar’, z=’baz’)
In this example, the values of the keyword arguments x, y, and z take the place of the replacement fields {x}, {y}, and {z}, respectively.
#you can specify keyword arguments in any arbitrary order: '{0}/{1}/{2}'.format('foo', 'bar', 'baz')
‘foo/bar/baz’
‘{0}/{2}/{1}’.format(‘bar’, ‘baz’, ‘foo’)
‘bar/foo/baz’
You can specify both positional and keyword arguments in one Python .format() call. Just note that, if you do so, then all the positional arguments must appear before any of the keyword arguments:
‘{0}{x}{1}’.format(‘foo’, ‘bar’, x=’baz’)
‘foobazbar’
#this will error out because keyword argument is mentioned before the positional one '{0}{x}{1}'.format('foo', x='baz', 'bar')
What is the output of the following?
‘{0}/{1}/{2}’.format(‘foo’, ‘bar’, ‘baz’)
‘foo/bar/baz’
what is the output of the following?
‘{2}.{1}.{0}/{0}{0}.{1}{1}.{2}{2}’.format(‘foo’, ‘bar’, ‘baz’)
‘baz.bar.foo/foofoo.barbar.bazbaz’
in Python string .format() method, what happens when you omit the numbers in the replacement fields like shown below?
’{}/{}/{}’.format(‘foo’, ‘bar’, ‘baz’)
you can omit the numbers in the replacement fields, in which case the interpreter assumes sequential order. This is referred to as automatic field numbering:
’{}/{}/{}’.format(‘foo’, ‘bar’, ‘baz’)
‘foo/bar/baz’
Please note: When you specify automatic field numbering, you must provide at least as many arguments as there are replacement fields:
What happens when you provide less replacement fields and more arguments in the .format() method like shown below?
’{}{}’.format(‘foo’, ‘bar’, ‘baz’)
’{}{}’.format(‘foo’, ‘bar’, ‘baz’)
‘foobar’
Here, the argument ‘baz’ is ignored.
What happens when you run the following code? please give reasons.
‘{0}{x}{1}’.format(‘foo’, x=’baz’, ‘bar’)
#this will error out because keyword argument is mentioned before the positional one '{0}{x}{1}'.format('foo', x='baz', 'bar')
When giving both positional and keyword arguments the positional arguments will always come before keyword arguments.
What are the components of the replacement field in python .format() method?
A replacement field consists of three components:
{[< name >] [!< conversion >] [:< format_spec >]}
These components are interpreted as follows:
Component Meaning
< name > Specifies the source of the value
to be formatted
< conversion > Indicates which standard Python
function to use to perform the
conversion
< format_spec > Specifies more detail about how
the value should be converted
Each component is optional and may be omitted.
What is the name component of the replacement field of .format() method?
The component is the first portion of a replacement field:
{[< name >][!< conversion >][:< format_spec >]}
indicates which argument from the argument list is inserted into the Python format string in the given location. It’s either a number for a positional argument or a keyword for a keyword argument.
In the following example, the components of the replacement fields are 0, 1, and baz, respectively:
x, y, z = 1, 2, 3
‘{0}, {1}, {baz}’.format(x, y, baz=z)
‘1, 2, 3’
If an argument is a list, then you can use indices with to access the list’s elements:
a = [‘foo’, ‘bar’, ‘baz’]
‘{0[0]}, {0[2]}’.format(a)
‘foo, baz’
‘{my_list[0]}, {my_list[2]}’.format(my_list=a)
‘foo, baz’
Similarly, you can use a key reference with if the corresponding argument is a dictionary:
d = {‘key1’: ‘foo’, ‘key2’: ‘bar’}
d[‘key1’]
‘{0[key1]}’.format(d)
‘foo’
What is the conversion component of the replacement field for python .format() method?
The < conversion > component is the middle portion of a replacement field:
{[< name>][!< conversion>][:< format_spec>]}
Python can format an object as a string using three different built-in functions:
1. str()
2. repr()
3. ascii()
By default, the Python .format() method uses str(), but in some instances, you may want to force .format() to use one of the other two. You can do this with the component of a replacement field. The possible values for are shown in the table below:
Value Meaning
!s Convert with str()
!r Convert with repr()
!a Convert with ascii()
The following examples force Python to perform string conversion using str(), repr(), and ascii(), respectively:
‘{0!s}’.format(42)
‘42’
‘{0!r}’.format(42)
‘42’
‘{0!a}’.format(42)
‘42’
In many cases, the result is the same regardless of which conversion function you use, as you can see in the example above. That being said, you won’t often need the component, so you won’t spend a lot of time on it here. However, there are situations where it makes a difference, so it’s good to be aware that you have the capability to force a specific conversion function if you need to.
What is the format spec component of the replacement field of the .format() method?
The < format_spec > component is the last portion of a replacement field:
{[< name>][!< conversion>][:< format_spec>]}
< format_spec > represents the guts of the Python .format() method’s functionality. It contains information that exerts fine control over how values are formatted prior to being inserted into the template string. The general form is this:
:[[< fill >]< align >][< sign >][#][0][< width >][< group >][.< prec >][< type >]
The ten subcomponents of are specified in the order shown. They control formatting as described in the table below:
Subcomponent Effect
: Separates the from the
rest of the replacement field
< fill > Specifies how to pad values that don’t
occupy the entire field width
< align > Specifies how to justify values that
don’t occupy the entire field width
< sign > Controls whether a leading sign is
included for numeric values # Selects an alternate output form for certain
presentation types
0 Causes values to be padded on the left
with zeros instead of ASCII space
characters
< width > Specifies the minimum width of the output
< group > Specifies a grouping character for numeric
output
.< prec > Specifies the number of digits after the
decimal point for floating-point
presentation types, and the
maximum output width for string
presentations types
< type > Specifies the presentation type, which is
the type of conversion performed on the
corresponding argument
These functions are analogous to the components you’ll find in the string modulo operator’s conversion specifier, but with somewhat greater capability.
Mention the values which can be used in the Type subcomponent of format_spec component of the .format() method?
The subcomponent specifies the presentation type, which is the type of conversion that’s performed on the corresponding value to produce the output. The possible values are shown below:
Value Presentation Type
============= ==================
b Binary integer
c Single character
d Decimal integer
e or E Exponential
f or F Floating point
g or G Floating point or Exponential
o Octal integer
s String
x or X Hexadecimal integer
% Percentage
’‘.format(42)
‘42’
’‘.format(42)
‘101010’
’‘.format(2.1)
‘2.100000’
’‘.format(‘foobar’)
‘foobar’
’‘.format(31)
‘1f’
What are fill and align subcomponent of format_spec component of the .format() method?
< fill > and < align > control how formatted output is padded and positioned within the specified field width. These subcomponents only have meaning when the formatted field value doesn’t occupy the entire field width, which can only happen if a minimum field width is specified with < width >. If < width > isn’t specified, then < fill > and <align> are effectively ignored. You’ll cover < width > later on in this tutorial.</align>
What are possible values for the align subcomponent of format_spec component of the .format() method?
Here are the possible values for the < align > subcomponent:
<
>
=
A value using the less than sign (<) indicates that the output is left-justified:
‘{0:<8s}’.format(‘foo’)
‘foo ‘
‘{0:<8d}’.format(123)
‘123 ‘
A value using the greater than sign (>) indicates that the output should be right-justified:
‘{0:>8s}’.format(‘foo’)
’ foo’
Please Note: Left Alignment is the default behaviour of strings and right alignment is the default behaviour of integers
A value using a caret (^) indicates that the output should be centered in the output field:
‘{0:^8s}’.format(‘foo’)
’ foo ‘
Finally, you can also specify a value using the equals sign (=) for the < align > subcomponent. This only has meaning for numeric values, and only when a sign is included in the output.
When numeric output includes a sign, it’s normally placed directly to the left of the first digit in the number, as shown above. If < align > is set to the equals sign (=), then the sign appears at the left edge of the output field, and padding is placed in between the sign and the number:
‘{0:+8d}’.format(123)
’ +123’
‘{0:=+8d}’.format(123)
’+ 123’
Complete the following code to get the output shown below
- ‘{0:? ? 8s}’.format(‘foo’)
’—–foo’
- ‘{0:? ?8d}’.format(123)
‘123#####’
- ‘{0:? ?8s}’.format(‘foo’)
’**foo***’
- ‘{0:->8s}’.format(‘foo’)
’—–foo’
- ‘{0:#<8d}’.format(123)
‘123#####’
- ‘{0:*^8s}’.format(‘foo’)
’**foo***’