Geek Slack

Introduction to Python
About Lesson



Python String Formatting


Python String Formatting

String formatting in Python allows you to create dynamic strings by embedding variables and expressions within other strings.

1. Using the % Operator

The % operator is used for string formatting in Python. You can use placeholders within a string and pass values to replace those placeholders.

Example:

name = "Alice"
age = 30

message = "My name is %s and I am %d years old." % (name, age)
print(message)

Output: My name is Alice and I am 30 years old.

2. Using the format() Method

The format() method provides a more flexible way of formatting strings. You can use placeholders or named placeholders within a string and pass values using positional or keyword arguments.

Example:

name = "Bob"
age = 25

message = "My name is {} and I am {} years old.".format(name, age)
print(message)

Output: My name is Bob and I am 25 years old.

3. Using f-strings (Python 3.6+)

f-strings provide a more concise and readable way of formatting strings in Python. You can embed variables and expressions directly within a string by prefixing it with f or F.

Example:

name = "Charlie"
age = 35

message = f"My name is {name} and I am {age} years old."
print(message)

Output: My name is Charlie and I am 35 years old.

Conclusion

String formatting in Python provides various methods for creating dynamic strings with embedded variables and expressions. Whether using the % operator, format() method, or f-strings, you can choose the most suitable approach based on readability and flexibility.

Join the conversation