Formatted printing

C-Style String Formatting in Python

Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios.

Basic Syntax

python

"format string" % (values)

Control Characters (Format Specifiers)

Format SpecifierDescriptionExampleOutput
%sString"%s" % "hello"hello
%dSigned decimal integer"%d" % 4242
%iSigned decimal integer"%i" % -10-10
%uUnsigned decimal integer"%u" % 1515
%oOctal integer"%o" % 810
%xHexadecimal (lowercase)"%x" % 255ff
%XHexadecimal (uppercase)"%X" % 255FF
%fFloating point decimal"%f" % 3.141593.141590
%eExponential notation (lowercase)"%e" % 10001.000000e+03
%EExponential notation (uppercase)"%E" % 10001.000000E+03
%gShorter of %f or %e"%g" % 0.000012341.234e-05
%GShorter of %f or %E"%G" % 0.000012341.234E-05
%cSingle character"%c" % 65A
%rString (repr() conversion)"%r" % "hello"'hello'
%%Literal % character"100%% complete"100% complete

Formatting Options

You can add modifiers between the % and the format character:

python

%[flags][width][.precision]specifier

Flags

  • - : Left-justify
  • + : Show sign
  • 0 : Zero-padding
  • : Space for positive numbers
  • # : Alternate form (e.g., 0x for hex)

Width & Precision

  • Integer before dot: minimum field width
  • Integer after dot: precision (decimal places for floats, max length for strings)

Examples

Basic Formatting

python

print("Name: %s, Age: %d" % ("Alice", 25))
# Output: Name: Alice, Age: 25

print("Hex: %x, Octal: %o" % (255, 8))
# Output: Hex: ff, Octal: 10

Number Formatting

python

print("Float: %f" % 3.14159)          # 3.141590
print("Float: %.2f" % 3.14159)        # 3.14
print("Padded: %05d" % 42)            # 00042
print("Signed: %+d" % 10)             # +10
print("Scientific: %.2e" % 1000)      # 1.00e+03

Alignment and Padding

python

print("Left: %-10s!" % "text")        # Left: text      !
print("Right: %10s!" % "text")        # Right:       text!
print("Zero-pad: %06d" % 123)         # 000123

Multiple Values

python

values = ("John", 30, 50000.50)
print("Name: %s, Age: %d, Salary: %.2f" % values)
# Output: Name: John, Age: 30, Salary: 50000.50

Special Cases

python

print("Percent: %%")                  # Percent: %
print("Char: %c" % 65)                # Char: A
print("Repr: %r" % "hello\nworld")    # Repr: 'hello\nworld'

While Python now has more modern formatting methods (.format() and f-strings), C-style formatting remains useful for:

  • Legacy code maintenance
  • Situations requiring precise numeric formatting
  • Cases where you need compatibility with C-style format strings

Python str.format() Method

The str.format() method (introduced in Python 2.6) provides a powerful way to format strings with placeholders ({}). It’s more flexible than %-formatting and works in all Python versions (unlike f-strings).


Basic Syntax

python

"Text {} more text".format(value)
  • Uses {} as placeholders
  • Values are passed to .format() in order
  • Supports indexing, naming, and formatting options

1. Basic Positional Formatting

python

print("{} loves {}".format("Alice", "Python"))
# Output: Alice loves Python

2. Index-Based Formatting

python

print("{0} vs {1} (rematch: {0} vs {1})".format("Python", "Java"))
# Output: Python vs Java (rematch: Python vs Java)

3. Named Placeholders

python

print("Name: {name}, Age: {age}".format(name="Bob", age=30))
# Output: Name: Bob, Age: 30

4. Number Formatting (Floats)

python

print("Pi: {:.2f}".format(3.14159))
# Output: Pi: 3.14

5. Padding and Alignment

python

print("{:<10}|{:^10}|{:>10}".format("Left", "Center", "Right"))
# Output: Left      |  Center  |     Right

6. Zero-Padding Numbers

python

print("ID: {:05d}".format(42))
# Output: ID: 00042

7. Dictionary Unpacking

python

data = {"name": "Charlie", "score": 95}
print("Name: {name}, Score: {score}".format(**data))
# Output: Name: Charlie, Score: 95

8. List/Tuple Indexing

python

values = [10, 20, 30]
print("{0[0]}, {0[1]}, {0[2]}".format(values))
# Output: 10, 20, 30

9. Dynamic Formatting

python

for i in range(1, 4):
    print("{:{width}}".format(i*i, width=i))
# Output:
# 1
#  4
#   9

10. Combining Multiple Features

python

print("{name:*^20} scored {score:.1f}%".format(name="Alice", score=95.5))
# Output: *******Alice******** scored 95.5%

Key Formatting Specifiers

SpecifierMeaningExampleOutput
:dDecimal integer"{:d}".format(42)42
:fFloat"{:.2f}".format(3.14159)3.14
:xHexadecimal (lowercase)"{:x}".format(255)ff
:XHexadecimal (uppercase)"{:X}".format(255)FF
:bBinary"{:b}".format(5)101
:oOctal"{:o}".format(8)10
:%Percentage"{:.0%}".format(0.95)95%

Advantages of str.format()

✅ Works in all Python versions (unlike f-strings)
✅ More readable than %-formatting
✅ Supports complex formatting (alignment, number formats)
✅ Allows reusing values (by index/name)


When to Use str.format()?

  • When you need backward compatibility (Python 2.7/3.0+)
  • For complex formatting scenarios
  • When you need reusable templates with named placeholders

Comparison with Other Methods

Feature%-formattingstr.format()f-strings
ReadabilityPoorGoodExcellent
FlexibilityLimitedHighHigh
SpeedFastMediumFastest
Python 2.xYesYesNo
Python 3.xYesYes3.6+

Conclusion

While f-strings are preferred in Python 3.6+, str.format() remains valuable for:

  • Legacy code maintenance
  • Complex string templating
  • Cases requiring precise control over formatting

F-Strings in Python: T

F-strings (formatted string literals) were introduced in Python 3.6 (PEP 498) and provide a concise, readable way to embed expressions inside string literals using { }. They are faster than %-formatting and str.format().


Syntax of F-Strings

python

f"Text {expression} more text"
  • Start with f or F before the string.
  • Enclose expressions inside { }.
  • Supports variables, operations, functions, and formatting.

1. Basic Variable Insertion

python

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output:
My name is Alice and I am 25 years old.


2. Mathematical Expressions

python

a = 5
b = 10
print(f"The sum of {a} and {b} is {a + b}.")

Output:
The sum of 5 and 10 is 15.


3. Function Calls Inside F-Strings

python

def greet(name):
    return f"Hello, {name}!"

user = "Bob"
print(f"{greet(user)} How are you?")

Output:
Hello, Bob! How are you?


4. Formatting Numbers (Floats, Decimals)

python

pi = 3.1415926535
print(f"Pi rounded to 2 decimals: {pi:.2f}")

Output:
Pi rounded to 2 decimals: 3.14


5. Padding and Alignment

python

text = "Python"
print(f"Left: {text:<10}")   # Left-align
print(f"Right: {text:>10}")  # Right-align
print(f"Center: {text:^10}") # Center-align

Output:

text

Left: Python    
Right:     Python
Center:   Python  

6. Zero-Padding Numbers

python

num = 42
print(f"Padded with zeros: {num:05d}")

Output:
Padded with zeros: 00042


7. Date Formatting

python

from datetime import datetime
today = datetime.now()
print(f"Today is {today:%B %d, %Y}")

Output:
Today is July 29, 2023 (or current date)


8. Dictionary Access

python

user = {"name": "Alice", "age": 30}
print(f"Name: {user['name']}, Age: {user['age']}")

Output:
Name: Alice, Age: 30


9. Conditional Expressions

python

age = 17
print(f"{'Adult' if age >= 18 else 'Minor'}")

Output:
Minor


10. Multi-line F-Strings

python

name = "Charlie"
profession = "Engineer"
message = (
    f"Name: {name}\n"
    f"Job: {profession}\n"
    f"Status: {'Active' if True else 'Inactive'}"
)
print(message)

Output:

text

Name: Charlie
Job: Engineer
Status: Active

Key Advantages of F-Strings

✅ Faster than %-formatting and .format()
✅ More readable with embedded expressions
✅ Supports complex operations (functions, conditionals, math)
✅ Better debugging (Python 3.8+ allows {variable=})

Example (Python 3.8+ Debugging)

python

x = 10
print(f"{x=}")  # Output: x=10

When to Use F-Strings?

  • Python 3.6+ projects.
  • Fast string formatting with minimal syntax.
  • Dynamic string generation (e.g., logs, reports, SQL queries).

Conclusion

F-strings are the best way to format strings in modern Python. They are clean, fast, and powerful, replacing older methods like % and .format() in most cases.

Similar Posts

  • non-capturing group, Named Groups,groupdict()

    To create a non-capturing group in Python’s re module, you use the syntax (?:…). This groups a part of a regular expression together without creating a backreference for that group. A capturing group (…) saves the matched text. You can then access this captured text using methods like group(1), group(2), etc. A non-capturing group (?:…)…

  • Default Arguments

    Default Arguments in Python Functions Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead. Basic Syntax python def function_name(parameter=default_value): # function body Simple Examples Example 1: Basic Default Argument python def greet(name=”Guest”): print(f”Hello, {name}!”)…

  • For loop 13 and 14th class

    The range() Function in Python The range() function is a built-in Python function that generates a sequence of numbers. It’s commonly used in for loops to iterate a specific number of times. Basic Syntax There are three ways to use range(): 1. range(stop) – One Parameter Form Generates numbers from 0 up to (but not including) the stop value. python for i in range(5):…

  • Python Variables: A Complete Guide with Interview Q&A

    Here’s a detailed set of notes on Python variables that you can use to explain the concept to your students. These notes are structured to make it easy for beginners to understand. Python Variables: Notes for Students 1. What is a Variable? 2. Rules for Naming Variables Python has specific rules for naming variables: 3….

  • date time modules class55

    In Python, the primary modules for handling dates and times are: 🕰️ Key Built-in Modules 1. datetime This is the most essential module. It provides classes for manipulating dates and times in both simple and complex ways. Class Description Example Usage date A date (year, month, day). date.today() time A time (hour, minute, second, microsecond,…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

Leave a Reply

Your email address will not be published. Required fields are marked *