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

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • sqlite3 create table

    The sqlite3 module is the standard library for working with the SQLite database in Python. It provides an interface compliant with the DB-API 2.0 specification, allowing you to easily connect to, create, and interact with SQLite databases using SQL commands directly from your Python code. It is particularly popular because SQLite is a serverless database…

  • re module

    The re module is Python’s built-in module for regular expressions (regex). It provides functions and methods to work with strings using pattern matching, allowing you to search, extract, replace, and split text based on complex patterns. Key Functions in the re Module 1. Searching and Matching python import re text = “The quick brown fox jumps over the lazy dog” # re.search()…

  • Escape Sequences in Python

    Escape Sequences in Python Escape sequences are special character combinations that represent other characters or actions in strings. Here’s a complete list of Python escape sequences with two examples for each: 1. \\ – Backslash python print(“This is a backslash: \\”) # Output: This is a backslash: \ print(“Path: C:\\Users\\Name”) # Output: Path: C:\Users\Name 2. \’ – Single quote…

  • Class Variables Andmethds

    Class Variables Class variables are variables that are shared by all instances of a class. They are defined directly within the class but outside of any method. Unlike instance variables, which are unique to each object, a single copy of a class variable is shared among all objects of that class. They are useful for…

Leave a Reply

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