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

  • Quantifiers (Repetition)

    Quantifiers (Repetition) in Python Regular Expressions – Detailed Explanation Basic Quantifiers 1. * – 0 or more occurrences (Greedy) Description: Matches the preceding element zero or more times Example 1: Match zero or more digits python import re text = “123 4567 89″ result = re.findall(r’\d*’, text) print(result) # [‘123’, ”, ‘4567’, ”, ’89’, ”] # Matches…

  • 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…

  • Python and PyCharm Installation on Windows: Complete Beginner’s Guide 2025

    Installing Python and PyCharm on Windows is a straightforward process. Below are the prerequisites and step-by-step instructions for installation. Prerequisites for Installing Python and PyCharm on Windows Step-by-Step Guide to Install Python on Windows Step 1: Download Python Step 2: Run the Python Installer Step 3: Verify Python Installation If Python is installed correctly, it…

  • re.I, re.S, re.X

    Python re Flags: re.I, re.S, re.X Explained Flags modify how regular expressions work. They’re used as optional parameters in re functions like re.search(), re.findall(), etc. 1. re.I or re.IGNORECASE Purpose: Makes the pattern matching case-insensitive Without re.I (Case-sensitive): python import re text = “Hello WORLD hello World” # Case-sensitive search matches = re.findall(r’hello’, text) print(“Case-sensitive:”, matches) # Output: [‘hello’] # Only finds lowercase…

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

Leave a Reply

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