Python String Formatting Exercises
Python String Formatting Practice Questions
Which placeholder is used to insert an integer value when using the old-style % string formatting in Python?
In Python's old-style string formatting using the % operator:
%sis used for strings.%dis used for integers.%fis used for floating-point numbers.%ican also be used for integers, but %d is the standard and widely preferred.
Example:
age = 25 print("I am %d years old" % age) # Output: I am 25 years old
Key takeaway: Use %d for integers in old-style formatting, though modern Python prefers f-strings or .format().
Which of the following code snippets correctly formats a string using the .format() method to insert the value 25 into the text "I am 25 years old"?
# Correct usage of .format() method
age = 25
text = "I am {0} years old".format(age)
print(text) # Output: I am 25 years old
Formatting strings using the .format() method
- Option 1 – Incorrect: Uses
{}but passes "25" as a string. Works, but not the intended numeric usage. - Option 2 – Correct: Uses
{0}placeholder and integer25, producing the intended output. - Option 3 – Incorrect: Uses old-style
%dformatting instead of.format(). - 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
25as 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:
nameandage. - 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 2 – Incorrect: Formats to 3 decimal places → "3.142".
- Option 3 – Incorrect: Uses .format() method instead of f-string.
- Option 4 – Correct: Uses f-string with
:.2fto format float to 2 decimal places → "3.14".
Step-by-step reasoning:
- Define float variable
pi = 3.14159. - Use f-string with
:.2fto format to 2 decimal places. - Python evaluates the expression and rounds to 2 decimal places → "3.14".
Key takeaways:
:.Nfformats 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
%sfor strings,%dfor integers, and%ffor 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
%fplaceholder. - 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:
%sfor name (string) and%dfor 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)
Center-aligning strings with .format()
- Option 1 – Incorrect:
<:10is invalid syntax; left-align uses{:<10}. - Option 2 – Incorrect:
>:10is invalid syntax; right-align uses{:>10}. - Option 3 – Correct:
{:^10}centers the string "text" within a total width of 10 characters, adding spaces equally on both sides. - Option 4 – Incorrect:
{:<10}left-aligns text; it does not fill with zeros by default.
Step-by-step reasoning:
- Define the string:
text = "Solviyo". - Use
{:^10}to center-align within a width of 10. - Python adds spaces to both sides so total length = 10 → ' Solviyo '.
Key takeaways:
{:→ left-align, {:>N}→ right-align,{:^N}→ center-align.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:
.10fformats to 10 decimal places, not total width 10. - Option 2 – Incorrect:
10fspecifies total width 10 but defaults to 6 decimal places → "123.456789". - Option 3 – Incorrect:
.2is incomplete; missingftype specifier. - Option 4 – Correct:
:10.2fformats 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 thef"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.- F-strings allow expressions directly inside curly braces, increasing convenience.
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?
# Example of string padding
text = "Solviyo"
left_aligned = text.ljust(10)
right_aligned = text.rjust(10)
center_aligned = text.center(10)
print(f"'{left_aligned}'")
print(f"'{right_aligned}'")
print(f"'{center_aligned}'")
# Output:
# 'Solviyo '
# ' Solviyo'
# ' Solviyo '
String padding using ljust, rjust, and center
- 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,centerfor 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 3 – Incorrect: Uses
.format()instead of f-strings; question specifies f-strings. - 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:
nameas string,scoreas 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.
- Supports alignment, width, precision, and complex expressions directly inside curly braces.
- 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→ indexiand wordword. - 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-elseinside 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
:.2for similar specifiers. - Option 4 – Incorrect: Variables are automatically converted to string representations; manual conversion is not required.
Step-by-step reasoning:
- Define variables
aandb. - Inside f-string:
{a + b}→ evaluates arithmetic → 10. - Inside f-string:
{a / b:.2f}→ evaluates division → formatted to 2 decimal places → 2.33. - 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 fromitolen(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 withword[::-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.findallto 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**2and cubei**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
:>widthfor right alignment,:for left. Consistent width ensures table-like formatting.Useful for printing reports, scores, or numeric tables in console applications.
Explore More Python Exercises
You may also like these Python exercises:
Test Your Python String Formatting Knowledge
Practicing Python String Formatting? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python – String Formatting
String formatting is one of those skills in Python that you end up using almost everywhere, whether you’re writing simple scripts or working on larger applications. At Solviyo, we’ve created a complete set of Python string formatting exercises with explanations and answers to help you learn this topic in depth. Our approach is straightforward: instead of just showing you solutions, we walk you through the logic behind them, so you understand why the answer works.
We begin with the basics. You’ll practice simple formatting tasks such as inserting values into strings, aligning text, and controlling decimal places. These beginner-friendly exercises are designed to give you confidence with Python’s format() method as well as f-strings, which are now the most common way of formatting in modern Python. Each question comes with a detailed explanation and a correct answer, making sure you don’t just memorize but actually learn the concepts.
Once you’re comfortable, we move on to slightly more advanced formatting. This includes handling multiple variables, formatting numbers for readability, adding padding, working with percentages, and even formatting dates and times. These exercises reflect the kind of problems you’ll face in real-world projects—like displaying reports, generating user-friendly outputs, or handling currency values. Alongside these exercises, you’ll also find Python MCQs with answers and explanations to check your understanding quickly.
For learners who want to challenge themselves, we also include tricky formatting problems. These tasks involve combining text alignment with numeric formatting, nesting formatted strings, and exploring formatting options inside f-strings. You’ll even encounter scenarios where you need to dynamically build formats, which is especially useful in automation scripts. As always, every problem is supported with a clear explanation and answer to guide you through the thought process.
One of the things that make this topic so practical is how often it shows up in interviews and coding assessments. Employers want to see if you can present data neatly, generate reports, or make logs readable—and string formatting plays a big role in all of that. That’s why we’ve carefully mixed exercises and MCQs here at Solviyo: to give you both the hands-on coding practice and the quick checks that reinforce your knowledge.
By practicing consistently with our string formatting exercises, you’ll not only improve your coding style but also learn how to write cleaner and more efficient programs. Explore Solviyo’s set of Python string formatting exercises, explanations, and answers today, and take your Python skills to the next level.