Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python String Formatting: Three Practical Methods

Tech May 13 1

String formating in Python allows you to insert variables in to strings in a controllled manner. This tutorial covers the three most common approaches.

Method 1: Using the % Operator

The % operator is the oldest way to format strings in Python. The %s placeholder represents a string, while %d represents an integer. The number of placeholders must match the number of variables provided.

>>> user = "Alice"
>>> score = 95
>>> print("Student: %s, Score: %d" % (user, score))
Student: Alice, Score: 95

Multiple placeholders require parentheses around the variables.

Method 2: Using the format() Function

The format() method offers more flexibility. It accepts an arbitrary number of arguments, and positional indexes can be used to control the order.

>>> "{} {}".format("hello", "world")
'hello world'

>>> "{1} {0}".format("hello", "world")
'world hello'

>>> "{0} {1} {0}".format("hello", "world")
'hello world hello'

You can also use named parameters:

>>> print("Product: {name}, Price: {price}".format(name="Widget", price=29.99))
Product: Widget, Price: 29.99

Using dictionaries:

>>> data = {"item": "Laptop", "cost": 999}
>>> print("Item: {item}, Cost: {cost}".format(**data))
Item: Laptop, Cost: 999

Using lists with indices:

>>> inventory = ["Monitor", 199]
>>> print("Product: {0[0]}, Price: {0[1]}".format(inventory))
Product: Monitor, Price: 199

Using objects:

class Product:
    def __init__(self, id):
        self.id = id

item = Product(42)
print("Product ID: {0.id}".format(item))

Output:

Product ID: 42

Method 3: Using f-string

F-strings, introduced in Python 3.6, provide the most concise syntax. Prefix the string with f and embed variables directly within curly braces.

>>> name = "Bob"
>>> quantity = 5
>>> print(f"Item: {name}, Quantity: {quantity}")
Item: Bob, Quantity: 5

F-strings support expressions and function calls within the placeholders:

>>> price = 100
>>> tax = 0.08
>>> print(f"Total: {price + (price * tax):.2f}")
Total: 108.00

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.