0 Comments

Introduction

String formatting in Python is a fundamental skill for creating dynamic and readable strings. Python provides multiple techniques to format strings, such as the format() method, f-strings, and the older %-style formatting. This guide explores these approaches with practical examples and real-world applications.

String Formatting Methods

1. Using the format() Method

The format() method is a versatile way to insert variables into strings.

Syntax

string.format(value1, value2, ...)

Example

# Example
name = "Alice"
age = 30
result = "My name is {} and I am {} years old.".format(name, age)
print(result)

Output:

My name is Alice and I am 30 years old.

Positional and Keyword Arguments

# Using positional arguments
result = "{0} is learning {1}.".format("Alice", "Python")

# Using keyword arguments
result = "{name} is {age} years old.".format(name="Alice", age=30)
print(result)

Output:

Alice is 30 years old.

2. Using F-Strings (Python 3.6+)

F-strings provide a concise and efficient way to format strings using embedded expressions. They are denoted by prefixing the string with f.

Example

# Example
name = "Alice"
age = 30
result = f"My name is {name} and I am {age} years old."
print(result)

Output:

My name is Alice and I am 30 years old.

Using Expressions

# Example
result = f"The sum of 5 and 3 is {5 + 3}."
print(result)

Output:

The sum of 5 and 3 is 8.

3. Using %-Style Formatting

The % operator provides an older style of string formatting. While it is less commonly used today, it is still worth knowing.

Example

# Example
name = "Alice"
age = 30
result = "My name is %s and I am %d years old." % (name, age)
print(result)

Output:

My name is Alice and I am 30 years old.

Advanced String Formatting

Padding and Alignment

# Example
result = "|{:^10}|".format("Python")
print(result)

Output:

|  Python  |

Formatting Numbers

# Example
result = "The value of pi is approximately {:.2f}.".format(3.14159)
print(result)

Output:

The value of pi is approximately 3.14.

Interview Questions

  • Question 1: What are the advantages of f-strings over the format() method?
  • Question 2: How would you format a string to align text to the left, right, or center?
  • Question 3: Write a Python program to format a string with dynamic precision for floating-point numbers.
  • Question 4: What is the difference between %-style formatting and f-strings?
  • Question 5: How can you include curly braces {} in a formatted string?

Conclusion

String formatting is an essential skill for any Python programmer. Whether you use the format() method, f-strings, or %-style formatting, understanding these techniques will help you write cleaner and more dynamic code. Choose the method that best fits your use case and Python version.

Leave a Reply

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

Related Posts