DEV Community

qing
qing

Posted on

2-Minute Python Guide: f-strings

2-Minute Python Guide: f-strings

Python's f-strings provide a powerful way to embed expressions inside string literals. Introduced in Python 3.6, they have become a staple in Python development.

Basic Interpolation

You can use f-strings to insert variables into strings. Here's a simple example:

name = "John"
age = 30
print(f"My name is {name} and I'm {age} years old.")
Enter fullscreen mode Exit fullscreen mode

This will output: "My name is John and I'm 30 years old."

Expressions

F-strings can also evaluate expressions:

x = 5
y = 3
print(f"The sum is {x + y}")
Enter fullscreen mode Exit fullscreen mode

This will output: "The sum is 8"

Format Specs

You can use format specs to format the output:

pi = 3.14159
print(f"The value of pi is {pi:.2f}")
Enter fullscreen mode Exit fullscreen mode

This will output: "The value of pi is 3.14"

Multiline f-strings

F-strings can span multiple lines:

name = "John"
age = 30
print(f"""
My name is {name}
and I'm {age} years old.
""")
Enter fullscreen mode Exit fullscreen mode

This will output:

My name is John
and I'm 30 years old.
Enter fullscreen mode Exit fullscreen mode

Takeaway: f-strings are a game-changer for string formatting in Python. They provide a concise and readable way to embed expressions and format specs, making your code more efficient and easier to maintain. Start using f-strings in your Python projects today!


Follow me on Dev.to for daily Python tips and quick guides!


If you found this useful, you might like Python Automation Scripts Pack (10 Ready-to-Use Tools) — a practical resource that takes things a step further. At $19.99 it's a solid investment for your toolkit.


喜欢这篇文章?关注获取更多Python自动化内容!

Top comments (0)