The Easiest Way to Format Strings with F-Strings

281次阅读
没有评论

After working with variables and lists, you’ll often need to display them within a sentence or a message. Today, we’ll cover the most modern and readable way to format strings in Python: f-strings.

In the past, you might have formatted strings using the % operator or the .format() method:

Python

name = "Alex"
age = 30

# Using the .format() method
print("My name is {} and I am {} years old.".format(name, age))

# Using the % operator
print("My name is %s and I am %d years old." % (name, age))
Both of these methods get the job done. However, they can become clumsy and hard to read, especially when you have many variables to insert. You have to look back and forth between the string and the variables at the end.

The Pythonic Way with f-strings

F-strings, or “formatted string literals,” were introduced in Python 3.6 and provide a simpler, more intuitive syntax. You simply prefix the string with the letter f and place your variables directly inside curly braces {}.

Python

name = "Alex"
age = 30

# The modern f-string way
print(f"My name is {name} and I am {age} years old.")
Why are f-strings better?
  1. Readability: The variables are placed exactly where they will appear in the string, making the code much easier to read and understand at a glance.
  2. Conciseness: The syntax is shorter and cleaner than older methods.
  3. Power: You can even put Python expressions directly inside the curly braces!

Python

print(f"In 5 years, Alex will be {age + 5} years old.")
# Output: In 5 years, Alex will be 35 years old.
F-strings are now the recommended way to format strings in Python for their simplicity and power. Start using them today to make your code more elegant. Check back tomorrow for another tip!
正文完
 0
评论(没有评论)
验证码