0% found this document useful (0 votes)
22 views3 pages

String Formatting

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views3 pages

String Formatting

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

String Formatting

In Python, string formatting can be done in several ways. Here's an overview of different methods, along
with examples of each:

1. Using % operator (Old style)

python

Copy code

name = "John"

age = 25

print("Hello, %s. You are %d years old." % (name, age))

2. Using .format() method (Preferred before Python 3.6)

python

Copy code

name = "John"

age = 25

print("Hello, {}. You are {} years old.".format(name, age))

You can also use positional arguments:

python

Copy code

print("Hello, {0}. You are {1} years old.".format(name, age))

Or named arguments:

python

Copy code

print("Hello, {name}. You are {age} years old.".format(name="John", age=25))

3. Using f-strings (Introduced in Python 3.6, concise and efficient)

python

Copy code

name = "John"

age = 25

print(f"Hello, {name}. You are {age} years old.")


4. Using str.format() with number formatting

You can also format numbers, for example, rounding floats or adding leading zeros:

python

Copy code

price = 49.99

print("The price is {:.2f} dollars.".format(price)) # Prints price with 2 decimal places

number = 7

print("The number is {:03}".format(number)) # Prints the number with leading zeros (e.g., 007)

Or using f-strings:

python

Copy code

price = 49.99

print(f"The price is {price:.2f} dollars.")

number = 7

print(f"The number is {number:03}")

5. Aligning Text with .format() and f-strings

You can also specify alignment within a string:

python

Copy code

print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))

# Same using f-string

print(f"{'Left':<10} | {'Center':^10} | {'Right':>10}")

Example of all formats combined:

python

Copy code

name = "Alice"
age = 30

balance = 1023.456

# Using % operator

print("Name: %s, Age: %d, Balance: %.2f" % (name, age, balance))

# Using .format() method

print("Name: {}, Age: {}, Balance: {:.2f}".format(name, age, balance))

# Using f-strings

print(f"Name: {name}, Age: {age}, Balance: {balance:.2f}")

Each method has its use cases, but f-strings are currently the most concise and recommended for
modern Python.

You might also like