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

  • Create a User-Defined Exception

    A user-defined exception in Python is a custom error class that you create to handle specific error conditions within your code. Instead of relying on built-in exceptions like ValueError, you define your own to make your code more readable and to provide more specific error messages. You create a user-defined exception by defining a new…

  • Keyword-Only Arguments in Python and mixed

    Keyword-Only Arguments in Python Keyword-only arguments are function parameters that must be passed using their keyword names. They cannot be passed as positional arguments. Syntax Use the * symbol in the function definition to indicate that all parameters after it are keyword-only: python def function_name(param1, param2, *, keyword_only1, keyword_only2): # function body Simple Examples Example 1: Basic Keyword-Only Arguments…

  • re.fullmatch() Method

    Python re.fullmatch() Method Explained The re.fullmatch() method checks if the entire string matches the regular expression pattern. It returns a match object if the whole string matches, or None if it doesn’t. Syntax python re.fullmatch(pattern, string, flags=0) import re # Target string string = “The Euro STOXX 600 index, which tracks all stock markets across Europe including the FTSE, fell by…

  • Dot (.) ,Caret (^),Dollar Sign ($), Asterisk (*) ,Plus Sign (+) Metacharacters

    The Dot (.) Metacharacter in Simple Terms Think of the dot . as a wildcard that can stand in for any single character. It’s like a placeholder that matches whatever character is in that position. What the Dot Does: Example 1: Finding Words with a Pattern python import re # Let’s find all 3-letter words that end with “at” text…

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

  • Iterators in Python

    Iterators in Python An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dictionaries, and sets. An iterator can be thought of as a pointer to a container’s elements. To create an iterator, you use the iter() function. To get the next element from the iterator, you…

Leave a Reply

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