String Formatting in Python: Using format() and f-strings


Python format() Method Made Simple | Beginners Guide #pythontutorial


placeholder : Marked by {}, Our data is placed inside this by using the format.

Using string

Just place the given string at the placeholder.
my_str='Welcome {} plus2net'
print(my_str.format('to')) # Welcome to plus2net

Using more than one placeholder

my_str='Product : {} , Prise is Rs {}'
print(my_str.format('Mango','45'))
Output
Product : Mango , Prise is Rs 45

using indexes for placeholders

We can mark the positions for the placeholders
my_str='Price is Rs : {1} , Product {0}'
print(my_str.format('Mango','45'))
Output
Price is Rs : 45 , Product Mango

Alignment of formatted text

We kept one placeholder of 25 positions. We have one product name ‘Mango’ to display within this 25 position width. We will align our output in left , centre and right side of the available 25 position width.
my_str='Left Aligned Product  : {:<25},Price:45'
print(my_str.format('Mango'))

my_str='Right Aligned Product : {:>25},Price:45'
print(my_str.format('Mango'))

my_str='Center Aligned Product: {:^25},Price:45'
print(my_str.format('Mango'))
Output
Left Aligned Product  : Mango                    ,Price:45
Right Aligned Product :                     Mango,Price:45
Center Aligned Product:           Mango          ,Price:45

Convert Decimal to Binary, Hex, and Octal

Python’s format specifiers like {:b}, {:x}, {:X}, and {:o} make it easy to convert decimal numbers into different number systems. This is helpful for tasks like data encoding, debugging, and system-level programming.

bBinary format , base 2
cunicode chars
dDecimal format, base 10
oOctal format, base 8
xHex format, base 16 , lower case char
XHex format, base 16 , Upper case char
nSame as d but uses local settings for separator char
noneSame as d
my_str='Binary value from decimal is: {:b}'
print(my_str.format(10))

my_str='HEX value from decimal is {:X}'
print(my_str.format(30))

my_str='HEX value from decimal is {:x}'
print(my_str.format(30))

my_str='Octal value from decimal is {:o}'
print(my_str.format(30))
Output is here
Binary value from decimal is: 1010
HEX value from decimal is 1E
HEX value from decimal is 1e
Octal value from decimal is 36

Using decimal place

We can format to display 4 decimal places
my_str='Price is Rs :{my_price:.4f}'
print(my_str.format(my_price=120.75))
Output
Price is Rs :120.7500
Total space we can define along with decimal place. Note that in above code we used 8 positions including the decimal ( dot ) . Now we will format for 9 places ( in total including integer , dot and decimal place )
my_str='Price is Rs :{my_price:9.4f}'
print(my_str.format(my_price=120.75))
Output ( total 9 places so one place is left blank at left side of the value )
Price is Rs : 120.7500

Sign type for numbers

This is applicable only for numbers
+Show both + and - signs
-Show only - signs
spaceShow leading space for + and - signs for negative numbers
my_str="Sign numbers is {:-}"
print(my_str.format(-30))

my_str="Sign numbers is {:-}"
print(my_str.format(+30))

my_str="Sign numbers is {:+}"
print(my_str.format(30))

my_str="Sign numbers is {:+}"
print(my_str.format(-30))

my_str="Sign numbers is {: }"
print(my_str.format(30))

my_str="Sign numbers is {: }"
print(my_str.format(-30))
Output
Sign numbers is -30
Sign numbers is 30
Sign numbers is +30
Sign numbers is -30
Sign numbers is  30
Sign numbers is -30

Formatting for 1000 place

One comma to be added for every thousand place. Here is the input with output.
def format_number(number):
    return ("{:,}".format(number))
print(format_number(1000000)) # 1,000,000

Using input data from user

name = input("What is your name? ")
print("Welcome to our platform, {}!".format(name))

Using a list to create string

Create a list called my_names with the names 'Alex', 'Rabi', 'Raju', and 'Srinivas Rao'. Then, write a program that prints a welcome message for each person in the list using the format() method within a loop.
my_names=['Alex','Rabi','Raju','Srinivas Rao']
my_str='Welcome Mr  {} to our company'
for name in my_names:
    print(my_str.format(name))
Creating Personalized Email Templates: using multiple placeholders to create a dynamic email template for a product expiry notification.
name="Raju"
product = "Google Colab Pro"
expiry_date = "2024-12-31"
email_template = "Dear {}, your {} subscription will expire on {}."
print(email_template.format(name, product, expiry_date))
Output
Dear Srinivas Rao, your Google Colab Pro subscription will expire on 2024-12-31.
Displaying Currency Formats:using formatting codes to control decimal places and add currency symbols to a number.
price = 199.99
print("The price is ${:.2f}".format(price)) # Output: The price is $199.99
Using formatting codes to control decimal places and add currency symbols to a number.
student_name = "Alice"
total_marks = 485
percentage = 97.00
report_card = """
Student Name: {}
Total Marks: {}
Percentage: {:.2f}%
""".format(student_name, total_marks, percentage)
print(report_card)
Output
Student Name: Alice
Total Marks: 485
Percentage: 97.00%
Demonstrates how to use formatting codes for alignment and width to create a neatly organized table with product information.
data = [("Product A", 10, 25.99),
        ("Product B", 5, 12.49),
        ("Product C", 20, 5.99)]

print("{:<15} {:<10} {:<10}".format("Product", "Quantity", "Price"))
for product, quantity, price in data:
    print("{:<15} {:^10} {:>10.2f}".format(product, quantity, price))
Output
Product         Quantity   Price     
Product A           10          25.99
Product B           5           12.49
Product C           20           5.99

Using f-strings for String Formatting

From Python 3.6 onwards, f-strings provide a cleaner and more readable way to embed expressions inside string literals. The syntax uses a leading f or F before the string, and expressions are placed inside curly braces {}.

Basic Syntax
name = 'John'
age = 25
print(f"My name is {name} and I am {age} years old.")

This will output: My name is John and I am 25 years old.

Advantages of f-strings

  • More concise and readable than format()
  • Allows direct evaluation of expressions inside placeholders
  • Supports all formatting options used in format()

Examples of f-strings

Formatting Numbers
pi = 3.1415926535
print(f"Value of Pi: {pi:.2f}")

Output: Value of Pi: 3.14

Embedding Expressions
a = 5
b = 10
print(f"Sum of {a and b is {a + b}")

Output: Sum of 5 and 10 is 15

Using Dictionary Values
data = {'x': 100, 'y': 200}
print(f"X: {data['x']}, Y: {data['y']}")

Output: X: 100, Y: 200

Zero Padding and Alignment
num = 42
print(f"Zero padded: {num:05}")
print(f"Right aligned: {num:>5}")
print(f"Left aligned: {num:<5}")

Output:
Zero padded: 00042
Right aligned:    42
Left aligned: 42   

Conclusion

f-strings offer a powerful, readable, and efficient way to format strings in Python. While the format() method is still valid and widely used, f-strings are generally preferred for new Python code due to their simplicity and performance.


All Built in Functions in Python
max() Bitwise operators using format() int() float()



Podcast on Python Basics in Hindi Language


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer