Session 2 - Part 1 Flashcards
What is the term used to describe controlling text output and making it look nice in Python?
String formatting is the process of controlling text output and making it visually appealing in Python.
What is one way to print combinations of text and data in Python before the introduction of f-strings? - (3)
Joining them together with commas,
for example:
numberOfSubjects = 1022
print(“There were “, numberOfSubjects, “ participants”).
What are some drawbacks of using commas to combine text and data for output in Python? - (2)
Commas can be annoying and imprecise especially when trying to format output neatly
E.g., Unable to limit number of decimal places or centre things on screen
There were 1022 participants
What would be output of this code?
2.0 / 3.0 is roughly: 0.6666666666666666
Example image of:
Drawback of using commas to combine text and data for output in Python - unable to limit number of deciaml places example
What is a modern and preferred method for combining data and strings for output formatting in Python, beside using commas?
Using f-strings, which provide a more elegant and concise way to format output by embedding variables directly into strings.
What does f-strings stand for in Python?
An f-string, short for “formatted string literal,”
How do you create an f-string in Python?
Prefix the string with the letter ‘f’, (just before te quote marks) then use curly braces {} to enclose the variable names you want to include in the string.
What happens when an f-string is evaluated in Python?
When an f-string is evaluated, Python replaces the expressions enclosed within curly braces {} with their corresponding values at runtime, resulting in a formatted string.
Explain this code - (4)
the variable my_variable is assigned a value of 100.
Then, an f-string named foo is created, where the value of my_variable (100) is embedded within the string using curly braces {} .
When foo is printed, it will display the string “My variable contains the value 100”.
The ‘f’ prefix before the string indicates that it is an f-string, and Python replaces the expression {my_variable} within the string with the value of the variable during runtime.
What is the output of this code?
My variable contains the value 100
How can you include multiple variables in an f-string in Python?
Multiple variables can be included in an f-string by separating them with commas inside the curly braces {}.
Example of adding multiple variables in f-string in Python
What will be the output of this code?
My vars are Test, 15.0, 10
The way in which the variables are output in f-string depends on the
data type
Example
The way in which the variables are output in f-string depends on the data type
the float in this case is shown with a .0 on the end whilst the int is not.
Explain this code - (4):
three variables a, b, and c are assigned values.
a is assigned 10 (integer)
b is assigned 15.0 (float)
c is assigned ‘True’ (boolean value)
An f-string named mystr is then created, which includes these variables within curly braces {} inside the string.
When mystr is printed, it will display the formatted string “My vars are Test, 15.0, 10”, with the variables c, b, and a inserted into the string in the order specified
What does the term “formatting with f-strings” refer to in Python? - (2)
“Formatting with f-strings” in Python refers to using f-strings to manipulate the appearance of output, such as justifying text or formatting data, by adding specific formatting options after the variable name.
Formatting options always have a colon at the end of the variable name and then some numbers or characters.
What are two ways in which we want to format strings in f-string? - (2)
- Justifying text (for example, by making sure it takes up a certain amount of space for each variable). This is useful when we want to print tables of data
- Format the data itself - for example limiting the number of decimal place in a float or adding zeros to the start of an integer
How can you force a value to occupy a certain amount of space using f-strings in Python? -
By adding a colon followed by the desired width after the variable name inside curly braces {} in the f-string.
What would be output of this code?
Q: What does the following f-string do?
myvar = ‘Test’
print(f’==={myvar}===’)
This f-string prints the value of the variable myvar surrounded by equals signs, resulting in the output ===Test===.
Q: Explain the purpose of the following f-string
myvar = ‘Test’
print(f’==={myvar:20}===’): - (3)
The output ===Test === consists of the string “===” at the beginning and end, with the variable myvar (“Test”) occupying 20 spaces.
Output is:
===Test ===
Since the word “Test” has only 4 characters, it is followed by 16 spaces to fill the specified width.
How to change allignment of variable in f-string?
You can change the alignment by adding a character before the width number inside curly braces {} in the f-string:
What is the default alignment behavior of a string in f-strings?
By default, strings are left-centered in the space provided within an f-string.
What is left-alignment of string in f-string?
<: left aligned (the default so does not usually need to be specified)
What is right-alignment of string in f-string?
> : right aligned
What is centred-alignment of string in f-string?
^: centred
What is the output of the following f-string?
The output would be ===TestText ===, with the string “TestText” occupying 8 characters and the remaining 12 spaces filled with whitespace to the right, resulting in left alignment of string “TestText” within the specified width.
What is the output of the following f-string?
The output would be
‘=== TestText===’, with the string “TestText” occupying 8 characters and the remaining 12 spaces filled with whitespace to the left, resulting in right alignment of string “TestText” within the specified width.
What is output of the following f-string? - (2)
The output would be:
=== TestText ===
with the string “TestText” occupying 8 characters and evenly distributed whitespace of 12 spaces on each side, resulting in center alignment of string “TestText” within the specified width.
How does f-string handle space expansion when the inserted string is longer than the specified width?
F-strings expand the space to fit the entire string when it is longer than the specified width
What is the output of this code? - (3)
variable myvar containing the string ‘TestTextVeryLong’ is inserted into the f-string with a specified width of 5 characters
Despite the specified width being only 5 characters, Python expands the space to accommodate the entire string when necessary
So output becomes: ===TestTextVeryLong===
What is the output of this code? - (2)
534, the original content was 3 characters long, and the f-string expanded the width to 7 characters by adding 2 spaces on each side to center the content.
=== 534 ===
Print your own name, centered in space surrounded by stars (**) like this:
** Alex **
Using f-strings
What is the output of the code print(f’==={myvar:^7}===’) where myvar = 500000090? - (2)
The output is ===500000090===, which shows the large number 500000090 centered within a 7-character space.
Since the number itself is longer than the specified width, the f-string expands the space to accommodate the entire number, ensuring no truncation occurs.
What is the purpose of zero-padding integers in Python (using f-strings with numbers)? - (3)
Zero-padding integers involves adding leading zeros to the integer to ensure it fills a specific width.
This adding 0s before the number to fill the space rather than spaces
This is often useful when naming files to make sure that they sort correctly (e.g. if using participant numbers).
What is the output of the code print(f’{mynum:03}’) where mynum = 5? - (2)
The output is 005, which demonstrates the integer 5 zero-padded to fill a width of 3 characters
Since 5 is 1 character, it adds 3 zeros before to fill the width of 3 characters
How can you control the number of decimal places in floating point numbers using f-strings?
You can control the number of decimal places in floating point numbers by specifying the desired number of digits after the decimal point in the format specifier, such as {myval:10.4f}
What is the default alignment behavior of a numbers (integers, floats) in f-strings?
By default, strings are right-centered in the space provided within an f-string.
What is the output of
print(f’=={myval:10.4f}==’)
where myval = 10.219? - (3)
The output is
== 10.2190==
This displays the floating-point number 10.219 with a total width of 10 characters, including three leading spaces followed by the number with four digits after the decimal point.
The zero at the end is added to fill the specified precision of four decimal places.
What is the output of print(f’=={myval:7.4f}==’)
where myval = 10.219? - (2)
The output is ==10.2190==. This displays the floating-point number 10.219 with a total width of 7 characters, including the number itself with four digits after the decimal point.
Since the specified width is sufficient to accommodate the entire number, no leading or trailing spaces are added.
What is the output of print(f’=={myval:7.2f}==’)
where myval = 10.219? - (3)
The output is == 10.22==. This result is achieved because the formatting specifier 7.2f is used, indicating that the number should be displayed with a total width of 7 characters, including two digits after the decimal point.
Python rounds the number 10.219 to 10.22 to meet the specified formatting requirements - width and precision of decimal places
Additionally, two leading spaces are added to ensure that the number is properly aligned within the specified width.
What happens if you ask for fewer decimal places in f-strings in Python?
Python rounds the numbers to the specified number of decimal places
What is the output of the code print(f’==={myvar:10}===’) where myvar = 5? - (2)
The output is
=== 5===
This indicates that the output is right-aligned, with 9 spaces added before the number 5 to achieve a total width of 10 characters.
We can also use … in f-strings which is useful for dealing with large or small nubmers (e.g., femot-Tesla in MEG)
scientific notation
What character is used for scientific notation in f-strings?
The e formatting character is used for scientific notation in f-strings.
How is scientific notation represented using the “e” formatting character? - (2)
Scientific notation using the “e” formatting character is expressed as a number multiplied by 10 raised to a power, denoted by “e”.
For example, “1.0e-6” represents 1.0 × 10^(-6).
What is the output of the code print(f’==={myval:e}===’)
where myval = 0.000001?
The output is “===1.000000e-06===”, which represents the number 0.000001 in scientific notation.
How can you control the number of decimal places in scientific notation when using the “e” formatting character in f-string? - (2)
You can control the number of decimal places in scientific notation by specifying the desired precision after the colon, similar to using the “f” formatting character.
For example, print(f’==={myval:.1e}===’) will display the number in scientific notation with one decimal place.
What happens if the provided number of spaces is not sufficient for the number when using the “e” formatting character?
If the provided number of spaces is not sufficient for the number when using the “e” formatting character, extra spaces will be added to accommodate the full representation of the number.
What is the purpose of specifying “.1e” in the code print(f’==={myval:.1e}===’)?
Specifying “.1e” limits the number of decimal places to one in the scientific notation representation of the number.
What is the output of the code print(f’==={myval:.1e}===’) where myval = 0.000001? - (3)
The output is ===1.0e-06===.
This notation represents the number 0.000001 in scientific format, where “1.0” denotes the main numerical value, “e” signifies “times ten to the power of”, and “-06” indicates the exponent, signifying that the number is multiplied by 10 to the power of -6.
The “.1” specifier in the f-string limits the number of decimal places to one.
What is the output of the code print(f’==={myval:10.1e}===’) where myval = 0.000001? - (4)
he total width specified is 10 characters.
The scientific notation 1.0e-06 itself takes up 7 characters (1.0e-06).
To ensure right alignment within the total width of 10 characters, three additional spaces are added before the number.
Therefore, there are three spaces before the number 1.0e-06 to make up the total width of 10 characters.
What does ‘d’ mean in f-string formatting?
In f-string formatting, ‘d’ is used to specify that the value should be formatted as an integer.
What is the purpose of the f-string expression {part_id:03d} in the code - (2)
print(f’| P{part_id:03d} | {num_trials:3d} | {rt:8.3f} |’)?
The expression {part_id:03d} formats the integer value part_id with leading zeros to make it three characters wide.
For example, if part_id is 1, it will be formatted as ‘P001’.
What is the purpose of the f-string expression {num_trials:3d} in the code print(f’| P{part_id:03d} | {num_trials:3d} | {rt:8.3f} |’)? - (2)
The expression {num_trials:3d} right-aligns the integer value num_trials within a minimum width of three characters.
If the integer has fewer than three digits, it will be padded with spaces on the left.