Python f-strings called formatted string literals, have a more concise syntax and can be super helpful in string formatting. To create f-strings, you only need to add an f
or an F
before the opening quotes of your string.
f"This is an f-string {var_name} and {var_name}."
Note: F-strings are faster than the two most commonly used string formatting mechanisms, which are % formatting and str.format().
Python f-strings
Simple example code.
language = "Python"
website = "EyeHunts.com"
print(f"I'm learning {language} from {website}.")
Output:
Evaluate Expressions with Python f-Strings
Let’s do a multiplication of 2 numbers.
num1 = 83
num2 = 9
print(f"The product of {num1} and {num2} is {num1 * num2}.")
Output: The product of 10 and 9 is 90.
Use Conditionals if..else
statements
if condition:
# if condition is True
else:
# if condition is False
Or
<true_block> if <condition> else <false_block>
Example: number is even if it’s evenly divisible by 2.
num = 100;
print(f"Is num even: {True if num % 2 == 0 else False}")
Output: Is num even: True
Call Methods
author = "John"
a_name = author.title()
print(f"This is a book by {a_name}.")
Call Functions Inside
def choice(c):
if c % 2 == 0:
return "Learn Python!"
else:
return "Learn JavaScript!"
print(f"Tell me what I should learn: {choice(3)}")
Output: Tell me what I should learn: Learn JavaScript!
Python f-strings provide a concise and readable way to embed expressions within string literals. They are powerful, supporting a wide range of operations from simple variable substitution to complex expressions and formatting.
Do comment if you have any doubts or suggestions on this Python formate string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.