%
string formatting in Python?In Python's old-style string formatting using the %
operator:
%s
is used for strings.%d
is used for integers.%f
is used for floating-point numbers.%i
can 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()
.
.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
{}
but passes "25" as a string. Works, but not the intended numeric usage.{0}
placeholder and integer 25
, producing the intended output.%d
formatting instead of .format()
..format()
.Step-by-step reasoning:
{0}
corresponds to the first argument in .format()
.25
as the argument to .format()
."I am 25 years old"
.Key takeaways:
.format()
method allows flexible insertion of variables into strings.{0}
are useful for multiple arguments and reordering.f"..."
) as an alternative.
# 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
{age + 5}
.Step-by-step reasoning:
name
and age
.f"
and place variables in {}
.{}
and returns the formatted string.Key takeaways:
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
:.2f
to format float to 2 decimal places → "3.14".Step-by-step reasoning:
pi = 3.14159
.:.2f
to format to 2 decimal places.Key takeaways:
:.Nf
formats a float to N decimal places.%
) 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
%s
for strings, %d
for integers, and %f
for floats.%f
placeholder.Step-by-step reasoning:
%s
for name (string) and %d
for age (integer).(name, age)
.Key takeaways:
.format()
are generally preferred for readability..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()
<:10
is invalid syntax; left-align uses {:<10}
.>:10
is invalid syntax; right-align uses {:>10}
.{:^10}
centers the string "text" within a total width of 10 characters, adding spaces equally on both sides.{:<10}
left-aligns text; it does not fill with zeros by default.Step-by-step reasoning:
text = "Solviyo"
.{:^10}
to center-align within a width of 10.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.
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
.10f
formats to 10 decimal places, not total width 10.10f
specifies total width 10 but defaults to 6 decimal places → "123.456789"..2
is incomplete; missing f
type specifier.:10.2f
formats the float with width 10 and 2 decimal places → padded with spaces → ' 123.46'.Step-by-step reasoning:
123.456789
.10.2f
: 10 → total width, 2 → decimal places, f → float type.Key takeaways:
{value:width.precisionf}
.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
str.format()
can also evaluate expressions like {age + 5}
.str.format()
, not slower.str.format()
uses placeholders and passes arguments separately.str.format()
does not require an f-string prefix; only f-strings need the f"
prefix.Step-by-step reasoning:
name = "Solviyo"
, age = 25
.str.format()
: placeholders {}
are replaced with arguments in order.Key takeaways:
str.format()
is flexible for reordering or repeated arguments.
# 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
:>8.2f
.:>20
) and prices left-aligned (:<8.2f
), opposite of requirement..format()
instead of f-string; question asks for f-string.:<20
) and prices right-aligned (:>8.2f
) with 2 decimal places → neatly formatted table.Step-by-step reasoning:
products
.<20
→ left-align in width 20.>8.2f
→ right-align in width 8 with 2 decimal places.Key takeaways:
<
, right-align with >
, center-align with ^
.
# 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
.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
ljust()
left-aligns, not right-aligns.rjust()
right-aligns, not centers.ljust(width)
→ left-align, rjust(width)
→ right-align, center(width)
→ center-align in the given width.Step-by-step reasoning:
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:
ljust
, rjust
, center
for padding and alignment without 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
{name:<25}
left-aligns names in width 25, {salary:>10.2f}
right-aligns salaries in width 10 with 2 decimal places.:>25
) and salaries left-aligned (:<10.2f
), which is opposite of requirement..format()
instead of f-strings; question specifies f-strings.Step-by-step reasoning:
:<25
→ space added to right if needed.:>10.2f
→ rounded to 2 decimal places, padded on left.Key takeaways:
# 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
{score/100:.1%}
.<, >, ^
), width, and precision for numbers.Step-by-step reasoning:
name
as string, score
as float.{name:<10}
→ left-align in width 10.{score:>6.2f}
→ right-align in width 6 with 2 decimal places.{score/100:.1%}
→ expression evaluated inside curly braces → formatted as percentage.Key takeaways:
str.format()
for clarity and efficiency.
# 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
Step-by-step reasoning:
words
→ index i
and word word
.i % 2 == 1
→ odd index → lowercase; else → uppercase.end=" "
to keep them on the same line.Key takeaways:
enumerate()
for index-based operations in loops.if-else
inside curly braces enables dynamic formatting per element.
# 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
{a + b}
, perform arithmetic, and format numbers directly (e.g., {a / b:.2f}
).:.2f
or similar specifiers.Step-by-step reasoning:
a
and b
.{a + b}
→ evaluates arithmetic → 10.{a / b:.2f}
→ evaluates division → formatted to 2 decimal places → 2.33.Key takeaways:
str()
conversions and .format()
calls.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
for j in range(len(s))
starts from 0 → includes empty or incorrect substrings.for j in range(i)
→ j never reaches indices ≥ i → misses many substrings.for j in range(i, len(s))
→ correctly slices substrings from index i to j → generates all substrings.Step-by-step reasoning:
i
: starting index of substring.j
: ending index of substring, ranging from i
to len(s)-1
.s[i:j+1]
to include character at index j.Key takeaways:
s[i:j+1]
to include the end character.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
s.split()
, reverses each word with word[::-1]
, and joins them → preserves word order.Step-by-step reasoning:
["Solviyo", "Python", "Exercises"]
.["oyivloS", "nohtyP", "sesicrexE"]
."oyivloS nohtyP sesicrexE"
.Key takeaways:
s.split()
to process words individually.word[::-1]
→ common Python slicing trick." ".join(list)
to combine words into a string after transformation.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
split()
does not remove punctuation → 'Python' and 'Python,' treated as different words.re.findall(r'\b\w+\b', s.lower())
extracts all words in lowercase ignoring punctuation → counts frequencies accurately.Step-by-step reasoning:
r'\b\w+\b'
to extract words → ['solviyo', 'python', 'python', 'exercises'].Key takeaways:
re.findall
to extract words cleanly from a string.words.count(word)
gives a simple frequency map.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
word[-2:]
takes last 2 characters, word[:-2]
takes the rest → concatenated → rotates word correctly.Step-by-step reasoning:
Key takeaways:
word[-n:]
to extract last n characters." ".join()
reconstructs the final string.
# 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
:>6
→ right-align in width 6 for each column → neatly aligned table.Step-by-step reasoning:
i**2
and cube i**3
.{value:>6}
to right-align each value in width 6.Key takeaways:
:>width
for right alignment, : for left.
Consistent width ensures table-like formatting.
Useful for printing reports, scores, or numeric tables in console applications.
Practicing Python String Formatting? Don’t forget to test yourself later in our Python Quiz.
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.