</> Code Editor { } Code Formatter

Python String Formatting Exercises


1/20

Python String Formatting Practice Questions

Correct
0%

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:

  • %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().

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

MethodDescription
% OperatorOld-style formatting using placeholders (%s, %d, %f)
str.format()Modern method with {} placeholders; supports positional or named arguments
f-StringsPrefixed with f (Python 3.6+); embed variables or expressions directly
Advanced SpecifiersControl alignment, padding, precision, numeric base (binary, hex), etc.

Basic Examples (Code + Output)

MethodCode ExampleOutput
% Operator
name = "Sophia"
age = 29
print("My name is %s and I am %d years old." % (name, age))
My name is Sophia and I am 29 years old.
str.format()
product = "Laptop"
price = 850.75
print("Product: {}, Price: ${:.2f}".format(product, price))
Product: Laptop, Price: $850.75
f-String
city = "Tokyo"
temp = 23.456
print(f"Weather in {city}: {temp:.1f}°C")
Weather in Tokyo: 23.5°C
Named placeholders
data = {"first": "John", "last": "Doe"}
print("Name: {first} {last}".format(**data))
Name: John Doe

Advanced Examples (Code + Output)

ScenarioCode ExampleOutput
Padding & Alignment
name, score = "Liam", 95
print(f"|{name:<10}|{score:>5}|")
|Liam | 95|
Floating Point Precision
print(f"{3.1415926:.2f}")
3.14
Binary/Hex Conversion
num = 255
print(f"{num:b} {num:x}")
11111111 ff
Expressions in f-Strings
x = 5
print(f"Double of {x} is {x*2}")
Double of 5 is 10
Combining Variables
user = "Alice"
points = 45
print(f"{user} has {points} points")
Alice has 45 points

When to Use Which Method

MethodBest Use Case
% OperatorLegacy code or older Python versions
str.format()Flexible formatting: positional/named placeholders, numeric precision
f-StringsPython 3.6+, concise & readable, embed expressions directly

Common Formatting Use-Cases

  • Dynamic messages and user-friendly output
  • Tables, reports, and aligned text
  • Numeric formatting (decimal precision, rounding)
  • Combining multiple variables or computed values in strings
  • File paths, URLs, logs, and system messages

Best Practices

  • Prefer f-Strings if using Python 3.6+
  • Use format specifiers for alignment, padding, and precision
  • Sanitize external input before formatting to prevent errors
  • Keep formatting readable and maintainable for long strings


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.