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

  • Programs

    Weekly Wages Removing Duplicates even ,odd Palindrome  Rotate list Shuffle a List Python random Module Explained with Examples The random module in Python provides functions for generating pseudo-random numbers and performing random operations. Here’s a detailed explanation with three examples for each important method: Basic Random Number Generation 1. random.random() Returns a random float between 0.0 and 1.0 python import…

  • Random Module?

    What is the Random Module? The random module in Python is used to generate pseudo-random numbers. It’s perfect for: Random Module Methods with Examples 1. random() – Random float between 0.0 and 1.0 Generates a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive). python import random # Example 1: Basic random float print(random.random()) # Output: 0.5488135079477204 # Example…

  • re Programs

    The regular expression r’;\s*(.*?);’ is used to find and extract text that is located between two semicolons. In summary, this expression finds a semicolon, then non-greedily captures all characters up to the next semicolon. This is an effective way to extract the middle value from a semicolon-separated string. Title 1 to 25 chars The regular…

  • Tuples

    In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but unlike lists, they cannot be modified after creation (no adding, removing, or changing elements). Key Features of Tuples: Syntax: Tuples are defined using parentheses () (or without any brackets in some cases). python my_tuple = (1, 2, 3, “hello”) or (without…

  • re.findall()

    Python re.findall() Method Explained The re.findall() method returns all non-overlapping matches of a pattern in a string as a list of strings or tuples. Syntax python re.findall(pattern, string, flags=0) Key Characteristics: Example 1: Extracting All Numbers from Text python import retext = “I bought 5 apples for $3.50, 2 bananas for $1.25, and 10 oranges for $7.80.”result = re.findall(r”\d{3}”,…

Leave a Reply

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