String Formatting in Python Flashcards

1
Q

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

A

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:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

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

A

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')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the output of the following?

‘{0}/{1}/{2}’.format(‘foo’, ‘bar’, ‘baz’)

A

‘foo/bar/baz’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what is the output of the following?

‘{2}.{1}.{0}/{0}{0}.{1}{1}.{2}{2}’.format(‘foo’, ‘bar’, ‘baz’)

A

‘baz.bar.foo/foofoo.barbar.bazbaz’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

in Python string .format() method, what happens when you omit the numbers in the replacement fields like shown below?

’{}/{}/{}’.format(‘foo’, ‘bar’, ‘baz’)

A

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:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What happens when you provide less replacement fields and more arguments in the .format() method like shown below?

’{}{}’.format(‘foo’, ‘bar’, ‘baz’)

A

’{}{}’.format(‘foo’, ‘bar’, ‘baz’)

‘foobar’

Here, the argument ‘baz’ is ignored.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What happens when you run the following code? please give reasons.

‘{0}{x}{1}’.format(‘foo’, x=’baz’, ‘bar’)

A
#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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the components of the replacement field in python .format() method?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the name component of the replacement field of .format() method?

A

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’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the conversion component of the replacement field for python .format() method?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the format spec component of the replacement field of the .format() method?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Mention the values which can be used in the Type subcomponent of format_spec component of the .format() method?

A

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’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are fill and align subcomponent of format_spec component of the .format() method?

A

< 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 &lt; width &gt; later on in this tutorial.</align>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are possible values for the align subcomponent of format_spec component of the .format() method?

A

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’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

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***’

A
  • ‘{0:->8s}’.format(‘foo’)

’—–foo’

  • ‘{0:#<8d}’.format(123)

‘123#####’

  • ‘{0:*^8s}’.format(‘foo’)

’**foo***’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the sign subcomponent of format_spec component of the .format() method?

A

You can control whether a sign appears in numeric output with the <sign> component. For example, in the following, the plus sign (+) specified in the <format_spec> indicates that the value should always be displayed with a leading sign:</format_spec></sign>

‘{0:+6d}’.format(123)

’ +123’​

‘{0:+6d}’.format(-123)

’ -123’

Here, you use the plus sign (+), so a sign will always be included for both positive and negative values. If you use the minus sign (-), then only negative numeric values will include a leading sign, and positive values won’t:

‘{0:-6d}’.format(123)

  • ’ 123’*
  • ‘{0:-6d}’.format(-123)*

’ -123’

17
Q

What is the 0 subcomponent of format_spec component of the .format() method?

A

If output is smaller than the indicated field width and you specify the digit zero (0) in <format_spec>, then values will be padded on the left with zeros instead of ASCII space characters:</format_spec>

‘{0:05d}’.format(123)

‘00123’

‘{0:08.1f}’.format(12.3)

‘000012.3’

You’ll typically use this for numeric values, as shown above. However, it works for string values as well:

‘{0:>06s}’.format(‘foo’)

‘000foo’

18
Q

What is the width subcomponent of format_spec component of the .format() method?

A

< width> specifies the minimum width of the output field:

‘{0:8s}’.format(‘foo’)

‘foo ‘

‘{0:8d}’.format(123)

’ 123’

Note that this is a minimum field width. Suppose you specify a value that’s longer than the minimum:

‘{0:2s}’.format(‘foobar’)

‘foobar’

19
Q

What is the group subcomponent of format_spec component of the .format() method?

A

< group> allows you to include a grouping separator character in numeric output. For decimal and floating-point presentation types, <group> may be specified as either a comma character (,) or an underscore character (_). That character then separates each group of three digits in the output:</group>

‘{0:,d}’.format(1234567)

‘1,234,567’

‘{0:_d}’.format(1234567)

‘1_234_567’

‘{0:,.2f}’.format(1234567.89)

  • ‘1,234,567.89’*
  • ‘*{0:_.2f}’.format(1234567.89)
  • ‘1_234_567.89’*
20
Q

What is the Prec subcomponent of format_spec component of the .format() method?

A

< prec> specifies the number of digits after the decimal point for floating point presentation types:

‘{0:8.2f}’.format(1234.5678)

’ 1234.57’

‘{0:8.4f}’.format(1.23)

’ 1.2300’

21
Q

What is Nested Replacement Fields in .format() method?

A

Inside a replacement field, you can specify a nested set of curly braces ({}) that contains a name or number referring to one of the method’s positional or keyword arguments. That portion of the replacement field will then be evaluated at run-time and replaced using the corresponding argument.

w = 10
p = 2
‘{2:{0}.{1}f}’.format(w, p, 123.456)

’ 123.46’

Here, the < name> component of the replacement field is 2, which indicates the third positional parameter whose value is 123.456. This is the value to be formatted. The nested replacement fields {0} and {1} correspond to the first and second positional parameters, w and p. These occupy the < width> and < prec> locations in < format_spec> and allow field width and precision to be evaluated at run-time.

You can use keyword arguments with nested replacement fields as well. This example is functionally equivalent to the previous one:

w = 10
p = 2
‘{val:{wid}.{pr}f}’.format(wid=w, pr=p, val=123.456)

’ 123.46’

In either case, the values of w and p are evaluated at run-time and used to modify the . The result is effectively the same as this:

‘{0:10.2f}’.format(123.456)

’ 123.46’

Please note: the same approach can be used for any subcomponent in the .format() method as shown below

s = ‘*’
‘{1:{0}> 6d}’.format(s,-123)

’**-123’

22
Q

What is the python formatted string or f-string syntax?

A

An f-string looks very much like a typical Python string except that it’s prepended by the character f:

f’foo bar baz’

You can also use an uppercase F:

s = F’qux quux’ s

The effect is exactly the same. Just like with any other type of string, you can use single, double, or triple quotes to define an f-string:

f’foo’

f”bar”

f’'’baz’’’

23
Q

Give an example of how you can embed Python expressions in f-strings.

A

The magic of f-strings is that you can embed Python expressions directly inside them. Any portion of an f-string that’s enclosed in curly braces ({}) is treated as an expression. The expression is evaluated and converted to string representation, and the result is interpolated into the original string in that location:

s = ‘bar’ print(f’foo.{s}.baz’)

The interpreter treats the remainder of the f-string—anything not inside curly braces—just as it would an ordinary string. For example, escape sequences are processed as expected:

  • s = ‘bar’*
  • print(f’foo\n{s}\nbaz’)*

another example of f-strings

  • quantity = 6*
  • item = ‘bananas’*
  • price = 1.74*
  • print(f’{quantity} {item} cost ${price}’)*

using the format method the above is equivalent to the following

  • quantity = 6*
  • item = ‘bananas’*
  • price = 1.74*
  • print(‘{0} {1} cost ${2}’.format(quantity, item, price))*
24
Q

Give an example of variable embedding in Python f-strings?

A
  • quantity, item, price = 6, ‘bananas’, 1.74*
  • f’{quantity} {item} cost ${price}’*
25
Q

Give an example of embedding arithmetic expression in Python f-string

A

quantity, item, price = 6, ‘bananas’, 1.74

print(f’Price per item is ${price/quantity}’)

x = 6

print(f’{x} cubed is {x**3}’)

26
Q

is the following valid in Python?

  • a = [‘foo’, ‘bar’, ‘baz’]*
  • d = {‘foo’: 1, ‘bar’: 2}*
  • print(f’a = {a} | d = {d}’)*
A

yes

27
Q

is the following statements valid in python?

a = [‘foo’, ‘bar’, ‘baz’]

d = {‘foo’: 1, ‘bar’: 2}

print(f’First item in list a = {a[0]}’)

print(f’Last two items in list a = {a[-2:]}’)

print(f’List a reversed = {a[::-1]}’)

print(f”Dict value for key ‘bar’ is {d[‘bar’]}”)

A

yes

28
Q

Give an example of function and method calls in Python f-string

A
  • a = [‘foo’, ‘bar’, ‘baz’, ‘qux’, ‘quux’]*
  • print(f’List a has {len(a)} items’)*
  • s = ‘foobar’*
  • f’— {s.upper()} —’*
  • d = {‘foo’: 1, ‘bar’: 2}*
  • print(f”Dict value for key ‘bar’ is {d.get(‘bar’)}”)*
29
Q

Give an example of Conditional expressions in Python f-string

A

x = 3

y = 7

print(f’The larger of {x} and {y} is {x if x > y else y}’)

age = 13

f’I am {“a minor” if age < 18 else “an adult”}.’

30
Q

Give an example of how you add a literal curly brace in an f-string

A

To include a literal curly brace in an f-string, escape it by doubling it, the same as you would in a template string for Python’s .format() method:

z = ‘foobar’

f’{{ {z} }}’

31
Q

what is the ouput of the following? is it a valid Python code?

newline=’\n’
print(f’This string contains a {newline}double quote (“) character.’)

A

Yes its a valid code and the ouptut would be

  • This string contains a*
  • double quote (“) character.*