In Python, you can format strings in several ways. Here are a few common methods:
1. f-Strings (Python 3.6+)
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
2. str.format() Method
name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
3. Percent Formatting
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
4. Template Strings
from string import Template
name = "Alice"
age = 30
template = Template("My name is $name and I am $age years old.")
formatted_string = template.substitute(name=name, age=age)
print(formatted_string)
Summary
- f-Strings are the most modern and preferred way for their readability.
str.format()is versatile and works in older versions of Python.- Percent formatting is an older style but still valid.
- Template strings offer a way to create strings with placeholders.
Feel free to explore these methods further in your coding practice!
