Python Tip: f-strings
Tired of complex string formatting? Use f-strings for cleaner, faster, and more readable code.
Basic f-strings
F-strings (formatted string literals) allow you to quickly insert variables into strings. Just put an f before the string and use curly braces to insert variables.
name = "Bob"
age = 30
# Don't do this
mystring = "Hello, " + name + "! You are " + str(age) + " years old."
print(mystring)
# Do this instead
mystring = f"Hello, {name}! You are {age} years old."
print(mystring)
Hello, Bob! You are 30 years old.
Hello, Bob! You are 30 years old.
Wrap-Up
Now you can use f-strings to format strings with ease, precision, and readability.
Follow me for more tips.
Shep Bryan IV