Option 4 – Incorrect: Uses f-string formatting, not .format().
Step-by-step reasoning:
Identify placeholder style: {0} corresponds to the first argument in .format().
Pass 25 as the argument to .format().
String evaluates to "I am 25 years old".
Key takeaways:
The .format() method allows flexible insertion of variables into strings.
Numbered placeholders like {0} are useful for multiple arguments and reordering.
Modern Python also supports f-strings (f"...") as an alternative.
Which of the following statements about Python f-strings is correct?
# Example using f-string
name = "Solviyo"
age = 25
text = f"My name is {name} and I am {age} years old."
print(text)
# Output: My name is Solviyo and I am 25 years old.
Understanding Python f-strings
Option 1 – Incorrect: F-strings can include expressions inside curly braces, e.g., {age + 5}.
Option 2 – Incorrect: F-strings do not require the `.format()` method; they evaluate expressions directly.
Option 3 – Incorrect: F-strings are available from Python 3.6+, not Python 2.x.
Option 4 – Correct: Variables and expressions can be embedded directly within string literals, making f-strings concise and readable.
Step-by-step reasoning:
Define variables: name and age.
Use f-string syntax: prefix the string with f" and place variables in {}.
Python evaluates the expressions inside {} and returns the formatted string.
Key takeaways:
F-strings provide a readable, concise way to embed variables and expressions directly in strings.
Supports any valid Python expression inside the curly braces.
Available in Python 3.6+ and is generally preferred over `%` or `.format()` for new code.
Which of the following snippets correctly formats the float 3.14159 to display only 2 decimal places using an f-string?
# Formatting a float to 2 decimal places using f-string
pi = 3.14159
formatted = f"{pi:.2f}"
print(formatted)
# Output: 3.14
Formatting floats to a fixed number of decimal places
Option 1 – Incorrect: Formats to 1 decimal place → "3.1".
Option 3 – Incorrect: Uses .format() method instead of f-string.
Option 4 – Correct: Uses f-string with :.2f to format float to 2 decimal places → "3.14".
Step-by-step reasoning:
Define float variable pi = 3.14159.
Use f-string with :.2f to format to 2 decimal places.
Python evaluates the expression and rounds to 2 decimal places → "3.14".
Key takeaways:
:.Nf formats a float to N decimal places.
F-strings allow concise inline formatting of numbers.
Always check rounding behavior for precise display requirements.
Which of the following statements about old-style (%) string formatting in Python is correct?
# Example of old-style % formatting
name = "Solviyo"
age = 25
text = "My name is %s and I am %d years old." % (name, age)
print(text)
# Output: My name is Solviyo and I am 25 years old.
Old-style (%) string formatting in Python
Option 1 – Correct: Uses placeholders like %s for strings, %d for integers, and %f for floats.
Option 2 – Incorrect: Old-style formatting is available in all Python 2.x and 3.x versions; it does not require f-strings.
Option 3 – Incorrect: Floating-point numbers can be formatted using %f placeholder.
Option 4 – Incorrect: Placeholders are required for proper type conversion; otherwise it raises an error.
Step-by-step reasoning:
Identify the placeholders in the string: %s for name (string) and %d for age (integer).
Provide values as a tuple: (name, age).
Python substitutes values into the placeholders and returns the formatted string.
Key takeaways:
Old-style formatting is simple and concise for basic use cases.
Use correct placeholders to match the type of value being inserted.
For new code, f-strings or .format() are generally preferred for readability.
Which of the following statements about Python string alignment using .format() is correct?
# Example of center-aligning a string
text = "Solviyo"
formatted = "{:^10}".format(text)
print(formatted)
# Output: ' Solviyo ' (spaces added to both sides to center within width 10)
Useful for creating neatly formatted text tables or console output.
Width N defines total characters including the string itself and padding.
Which of the following snippets correctly formats the floating-point number 123.456789 to display exactly 2 decimal places and pad the total width to 10 characters using an f-string?
# Formatting a float to 2 decimal places and padding width to 10
num = 123.456789
formatted = f"{num:10.2f}"
print(formatted)
# Output: ' 123.46' (4 spaces padding + 123.46)
Formatting floats with fixed width and decimal places using f-strings
Option 1 – Incorrect: .10f formats to 10 decimal places, not total width 10.
Option 2 – Incorrect: 10f specifies total width 10 but defaults to 6 decimal places → "123.456789".
Option 3 – Incorrect: .2 is incomplete; missing f type specifier.
Option 4 – Correct: :10.2f formats the float with width 10 and 2 decimal places → padded with spaces → ' 123.46'.
Step-by-step reasoning:
Number to format: 123.456789.
Use 10.2f: 10 → total width, 2 → decimal places, f → float type.
Python rounds to 2 decimal places → 123.46, adds 4 spaces to make total width 10.
Key takeaways:
F-strings allow simultaneous control of width and precision: {value:width.precisionf}.
Width includes all characters (digits, decimal point, padding).
This is useful for aligning numerical columns in tables or reports.
Which of the following statements about the difference between str.format() and f-strings in Python is correct?
# Example comparing str.format() and f-string
name = "Solviyo"
age = 25
# Using str.format()
text1 = "My name is {} and I am {} years old".format(name, age)
# Using f-string
text2 = f"My name is {name} and I am {age} years old"
print(text1)
print(text2)
# Output:
# My name is Solviyo and I am 25 years old
# My name is Solviyo and I am 25 years old
Understanding the difference between str.format() and f-strings
Option 1 – Incorrect: str.format() can also evaluate expressions like {age + 5}.
Option 2 – Incorrect: F-strings are generally faster than str.format(), not slower.
Option 3 – Correct: F-strings embed variables and expressions directly inside the string literal, while str.format() uses placeholders and passes arguments separately.
Option 4 – Incorrect: str.format() does not require an f-string prefix; only f-strings need the f" prefix.
Step-by-step reasoning:
Define variables: name = "Solviyo", age = 25.
Using str.format(): placeholders {} are replaced with arguments in order.
Using f-strings: embed variables directly inside curly braces.
Both produce the same output, but f-strings are more concise and readable.
Key takeaways:
Use f-strings for concise and readable string formatting in Python 3.6+.
str.format() is flexible for reordering or repeated arguments.
Which of the following snippets correctly formats a table of product names and prices so that names are left-aligned in width 20 and prices are right-aligned in width 8 with 2 decimal places?
# Formatting a table with aligned product names and prices
products = [("Pen", 1.234), ("Notebook", 5.5), ("Eraser", 0.78)]
for name, price in products:
print(f"{name:<20}{price:>8.2f}")
# Output:
# Pen 1.23
# Notebook 5.50
# Eraser 0.78
Creating aligned tables using f-strings
Option 1 – Incorrect: Left-align of names is correct, but double-check width for prices; right-align should be explicitly :>8.2f.
Option 2 – Incorrect: Names are right-aligned (:>20) and prices left-aligned (:<8.2f), opposite of requirement.
Option 3 – Incorrect: Uses .format() instead of f-string; question asks for f-string.
Option 4 – Correct: Names left-aligned (:<20) and prices right-aligned (:>8.2f) with 2 decimal places → neatly formatted table.
Step-by-step reasoning:
Loop through each tuple in products.
For names: <20 → left-align in width 20.
For prices: >8.2f → right-align in width 8 with 2 decimal places.
Combine both in f-string → neatly aligned table output.
Key takeaways:
F-strings allow simultaneous control over alignment, width, and decimal precision.
Left-align with <, right-align with >, center-align with ^.
Useful for console reports, tables, and dashboards.
Which of the following statements about Python string formatting alignment is correct?
# Example of different alignments
text = "Solviyo"
left = f"{text:<10}" # Left-align in width 10
center = f"{text:^10}" # Center-align in width 10
right = f"{text:>10}" # Right-align in width 10
print(left) # 'Solviyo '
print(center) # ' Solviyo '
print(right) # ' Solviyo'
Understanding string alignment using f-strings
Option 1 – Incorrect: `<` left-aligns, not right-aligns.
Option 2 – Incorrect: `^` centers, not left-aligns.
Option 3 – Correct: Demonstrates left, center, and right alignment correctly
Option 4 – Incorrect: '>' right-aligns, not convert numbers.
Which of the following statements about Python string padding using .rjust(), .ljust(), and .center() is correct?
Option 1 – Incorrect: ljust() left-aligns, not right-aligns.
Option 2 – Incorrect: rjust() right-aligns, not centers.
Option 3 – Correct: ljust(width) → left-align, rjust(width) → right-align, center(width) → center-align in the given width.
Option 4 – Incorrect: None of these methods truncate the string; they only add padding if needed.
Step-by-step reasoning:
Define string: text = "Solviyo".
text.ljust(10) → adds spaces to the right → 'Solviyo '.
text.rjust(10) → adds spaces to the left → ' Solviyo'.
text.center(10) → adds spaces equally on both sides → ' Solviyo '.
Key takeaways:
Use ljust, rjust, center for padding and alignment without f-strings.
Padding helps in printing tables or aligned console output.
These methods do not truncate strings; they only add spaces if the string is shorter than the width.
Which of the following snippets correctly formats a list of employee names and salaries so that names are left-aligned in width 25 and salaries are right-aligned in width 10 with 2 decimal places using f-strings?
# Formatting a table of employee names and salaries
employees = [("Alice Johnson", 52345.678), ("Bob Smith", 45000.5), ("Charlie Brown", 38000)]
for name, salary in employees:
print(f"{name:<25}{salary:>10.2f}")
# Output:
# Alice Johnson 52345.68
# Bob Smith 45000.50
# Charlie Brown 38000.00
Aligning names and salaries in a formatted table
Option 1 – Correct: {name:<25} left-aligns names in width 25, {salary:>10.2f} right-aligns salaries in width 10 with 2 decimal places.
Option 2 – Incorrect: Names are right-aligned (:>25) and salaries left-aligned (:<10.2f), which is opposite of requirement.
Option 4 – Incorrect: Both names and salaries are center-aligned, which does not match the requirement.
Step-by-step reasoning:
Loop through each employee tuple.
Names: left-align using :<25 → space added to right if needed.
Salaries: right-align using :>10.2f → rounded to 2 decimal places, padded on left.
Combine in f-string → neatly formatted table output.
Key takeaways:
Use f-strings for precise control of alignment, width, and decimal precision.
Left-align text columns and right-align numeric columns for readable tables.
Ensures professional console/table output formatting in Python scripts.
Which of the following statements about string formatting using f-strings is correct?
# Example of f-string with expressions and formatting
name = "Solviyo"
score = 95.6789
text = f"{name:<10} | {score:>6.2f} | {score/100:.1%}"
print(text)
# Output:
# Solviyo | 95.68 | 95.7%
Understanding f-strings and their capabilities
Option 1 – Incorrect: F-strings do not truncate strings; they only pad if the string is shorter than the specified width.
Option 2 – Incorrect: F-strings can evaluate expressions directly, like {score/100:.1%}.
Option 3 – Incorrect: Variables can be any type; Python automatically converts them to string representation when using f-strings.
Option 4 – Correct: F-strings embed variables and expressions directly, and you can control alignment (<, >, ^), width, and precision for numbers.
Step-by-step reasoning:
Define variables: name as string, score as float.
Use {name:<10} → left-align in width 10.
Use {score:>6.2f} → right-align in width 6 with 2 decimal places.
Use {score/100:.1%} → expression evaluated inside curly braces → formatted as percentage.
Key takeaways:
F-strings provide a concise and readable way to format strings with embedded variables and expressions.
Preferred method for Python 3.6+ over str.format() for clarity and efficiency.
Which of the following snippets will correctly print a list of strings with alternating words in uppercase and lowercase using f-strings?
# Alternating uppercase and lowercase words
words = ["Solviyo", "Python", "Exercises", "Tutorials"]
for i, word in enumerate(words):
print(f"{word.lower() if i % 2 == 1 else word.upper()}", end=" ")
# Output:
# SOLVIYO python EXERCISES tutorials
Creating alternating case words using f-strings
Option 1 – Incorrect: Uppercases words at even indices, lowercase at odd, but index logic is reversed for the requirement.
Option 2 – Correct: Uppercases words at even indices and lowercases words at odd indices → matches alternating requirement.
Option 3 – Incorrect: Uppercases all words; no alternation.
Option 4 – Incorrect: Prints words as-is; no case change applied.
Step-by-step reasoning:
Enumerate through words → index i and word word.
Check index: i % 2 == 1 → odd index → lowercase; else → uppercase.
Use f-string to format each word inline.
Print words with end=" " to keep them on the same line.
Key takeaways:
Use enumerate() for index-based operations in loops.
F-strings allow inline conditional expressions for concise formatting.
Combining f-strings with if-else inside curly braces enables dynamic formatting per element.
Which of the following statements about Python string formatting with f-strings is correct?
# Example: f-strings evaluating expressions and formatting
a = 7
b = 3
result = f"Sum: {a + b}, Division: {a / b:.2f}"
print(result)
# Output:
# Sum: 10, Division: 2.33
Using f-strings for expressions and formatting
Option 1 – Correct: F-strings can evaluate expressions like {a + b}, perform arithmetic, and format numbers directly (e.g., {a / b:.2f}).
Option 2 – Incorrect: F-strings do not truncate strings; they only apply padding if needed.
Option 3 – Incorrect: Floating-point precision can be applied with :.2f or similar specifiers.
Option 4 – Incorrect: Variables are automatically converted to string representations; manual conversion is not required.
Output concatenates evaluated values into string directly.
Key takeaways:
F-strings allow inline evaluation of expressions.
Formatting for numbers and precision can be applied directly.
F-strings simplify code by eliminating separate str() conversions and .format() calls.
Which of the following snippets will correctly generate a list of all substrings of a given string s using list comprehension?
# Generate all substrings using list comprehension
s = "Solviyo"
substrings = [s[i:j+1] for i in range(len(s)) for j in range(i, len(s))]
print(substrings)
# Output:
# ['S', 'So', 'Sol', 'Solv', 'Solvi', 'Solviy', 'Solviyo', 'o', 'ol', 'olv', ...]
Generating all substrings of a string
Option 1 – Incorrect: for j in range(len(s)) starts from 0 → includes empty or incorrect substrings.
Option 2 – Incorrect: for j in range(i) → j never reaches indices ≥ i → misses many substrings.
Option 3 – Correct: for j in range(i, len(s)) → correctly slices substrings from index i to j → generates all substrings.
Option 4 – Incorrect: Only generates single-character substrings.
Step-by-step reasoning:
Outer loop i: starting index of substring.
Inner loop j: ending index of substring, ranging from i to len(s)-1.
Slice s[i:j+1] to include character at index j.
List comprehension collects all substrings → complete list.
Key takeaways:
Use nested loops in list comprehension to generate combinations or slices.
Pay attention to slice boundaries: s[i:j+1] to include the end character.
Tricky nested comprehensions are useful for substring generation, matrix operations, and combinatorial tasks.
Which of the following snippets will correctly reverse every word in a string s but maintain the word order?
# Reverse each word but maintain order
s = "Solviyo Python Exercises"
reversed_words = [word[::-1] for word in s.split()]
print(" ".join(reversed_words))
# Output:
# 'oyivloS nohtyP sesicrexE'
Reversing each word individually in a string
Option 1 – Incorrect: Iterates over each character, not words → output is individual characters reversed incorrectly.
Option 2 – Correct: Splits string into words using s.split(), reverses each word with word[::-1], and joins them → preserves word order.
Option 3 – Incorrect: Reverses entire string first, then splits → words order is reversed incorrectly.
Option 4 – Incorrect: Reverses the entire string as a single element → joins → does not reverse individual words.
Step-by-step reasoning:
Split string into words: ["Solviyo", "Python", "Exercises"].
Reverse each word: ["oyivloS", "nohtyP", "sesicrexE"].
Join reversed words with spaces: "oyivloS nohtyP sesicrexE".
Key takeaways:
Use s.split() to process words individually.
Reversing a word: word[::-1] → common Python slicing trick.
Use " ".join(list) to combine words into a string after transformation.
Which of the following snippets will correctly count the frequency of each word in a string s, ignoring case and punctuation?
# Count word frequency ignoring case and punctuation
import re
s = "Solviyo Python Python, exercises!"
words = re.findall(r'\b\w+\b', s.lower())
freq = {word: words.count(word) for word in words}
print(freq)
# Output:
# {'solviyo': 1, 'python': 2, 'exercises': 1}
Counting word frequency ignoring case and punctuation
Option 1 – Incorrect: split() does not remove punctuation → 'Python' and 'Python,' treated as different words.
Option 2 – Incorrect: Only lowercases words but punctuation remains → 'Python,' and 'Python' counted separately.
Option 3 – Incorrect: Splitting on ", " misses spaces and punctuation inconsistencies → incomplete word extraction.
Option 4 – Correct: re.findall(r'\b\w+\b', s.lower()) extracts all words in lowercase ignoring punctuation → counts frequencies accurately.
Step-by-step reasoning:
Convert string to lowercase → "solviyo python python, exercises!"
Use regex r'\b\w+\b' to extract words → ['solviyo', 'python', 'python', 'exercises'].
Count occurrences of each word using dictionary comprehension → {'solviyo': 1, 'python': 2, 'exercises': 1}.
Key takeaways:
Use re.findall to extract words cleanly from a string.
Lowercasing before counting ensures case-insensitive frequency counts.
Dictionary comprehension with words.count(word) gives a simple frequency map.
Which of the following snippets will correctly rotate the characters of each word in a string s by 2 positions to the right?
# Rotate characters of each word by 2 positions to the right
s = "Solviyo Python Exercises"
rotated = [''.join([word[-2:], word[:-2]]) for word in s.split()]
print(" ".join(rotated))
# Output:
# "yoSolviy onPyth esExercis"
Rotating characters in words using list comprehension
Option 1 – Correct: word[-2:] takes last 2 characters, word[:-2] takes the rest → concatenated → rotates word correctly.
Option 2 – Incorrect: Rotates characters to the left by 2 instead of right → output not as required.
Option 3 – Incorrect: Reverses entire word → not rotation.
Option 4 – Incorrect: Rotates by 1 character only → does not match requirement.
Step-by-step reasoning:
Split string into words → ["Solviyo", "Python", "Exercises"]
For each word, take last 2 characters → "yo", "on", "es"
Concatenate with the rest of the word → "yoSolviy", "onPyth", "esExercis"
Join rotated words with spaces → "yoSolviy onPyth esExercis"
Key takeaways:
Use negative slicing word[-n:] to extract last n characters.
List comprehension allows processing multiple words efficiently.
Joining words with " ".join() reconstructs the final string.
Which of the following snippets will correctly display a table of numbers with their squares and cubes, all aligned to the right in width 6?
# Display table of numbers with squares and cubes, right-aligned
for i in range(1, 6):
print(f"{i:>6}{i**2:>6}{i**3:>6}")
# Output:
# 1 1 1
# 2 4 8
# 3 9 27
# 4 16 64
# 5 25 125
Formatting numbers into a right-aligned table
Option 1 – Incorrect: No width specified → numbers not aligned.
Option 2 – Correct: Uses :>6 → right-align in width 6 for each column → neatly aligned table.
Option 3 – Incorrect: No width specified in .format() → columns not aligned.
Option 4 – Incorrect: % formatting without width → columns not aligned.
Step-by-step reasoning:
Loop from 1 to 5.
Compute square i**2 and cube i**3.
Use {value:>6} to right-align each value in width 6.
Print each line → columns aligned correctly.
Key takeaways:
f-strings support alignment with :>width for right alignment, :for left.
Consistent width ensures table-like formatting.
Useful for printing reports, scores, or numeric tables in console applications.
Quick Recap of Python String Formatting Concepts
If you are not clear on the concepts of String Formatting, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
What Is String Formatting in Python
String formatting allows you to dynamically insert variables, expressions, or data into strings. This is essential for building meaningful output, logs, or reports. Python offers multiple formatting approaches to suit different needs.
Methods of String Formatting
Method
Description
% Operator
Old-style formatting using placeholders (%s, %d, %f)
str.format()
Modern method with {} placeholders; supports positional or named arguments
f-Strings
Prefixed with f (Python 3.6+); embed variables or expressions directly
Advanced Specifiers
Control alignment, padding, precision, numeric base (binary, hex), etc.
Basic Examples (Code + Output)
Method
Code Example
Output
% Operator
name = "Sophia"
age = 29
print("My name is %s and I am %d years old." % (name, age))
Practicing Python String Formatting? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python String Formatting Exercises
Welcome to Solviyo’s Python String Formatting exercises, designed to help you master a crucial skill for writing readable and professional Python code. From simple value insertion to advanced formatting techniques, these exercises include explanations, answers, and interactive Python MCQs to ensure deep understanding.
What You Will Learn
In this set of Python String Formatting exercises, you will explore:
Basic string formatting with the format() method and f-strings.
Aligning text, controlling decimal places, and inserting variables into strings.
Advanced formatting tasks such as handling multiple variables, padding, percentages, and formatting dates and times.
Tricky formatting scenarios including nested formatted strings, dynamic formats, and combining alignment with numeric formatting.
Applying formatting in real-world tasks like generating reports, displaying user-friendly outputs, and automating scripts.
Reinforcing concepts with interactive Python MCQs and explanations to check your understanding.
Why Learning Python String Formatting Matters
String formatting is a critical Python skill. It allows you to present data neatly, generate readable logs, create reports, and write professional code. Mastering formatting improves coding style, enhances readability, and prepares you for coding interviews, assessments, and real-world programming projects.
Start Practicing Python String Formatting Today
By completing these exercises, you will gain confidence in formatting strings efficiently in Python. Each exercise includes detailed explanations and answers to ensure you understand the logic behind each solution. Start practicing Python String Formatting exercises now and take your Python programming skills to the next level while preparing for practical applications and coding interviews.
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.