F-strings, also known as formatted string literals, were introduced in Python 3.6 as a way to simplify string interpolation and formatting.
As programmers, we typically deal with all kinds of string data, for message, debugs, user interaction, instructions, data display, charts, tables, etc. most and sometimes all of these need all kinds of data formatting so this is where String formatting and now, F-strings come in.
name = "Agile Python"
print(f"Hello, {name}!")
The f-string is a normal string, but the f prefix gives much simpler formatting options now, and makes the strings more readable as the keywords are right inline the string text.
>>> name = "Jane"
>>> age = 25
>>> f"Hello, {name}! You're {age} years old."
'Hello, Jane! You're 25 years old.'
>>> f"{2 * 21}"
'42'
>>> sep = "_"
>>> f"User's thousand separators: {integer:{sep}}"
'User's thousand separators: -1_234_567'
>>> floating_point = 1234567.9876
>>> f"Comma as thousand separators and two decimals: {floating_point:,.2f}"
'Comma as thousand separators and two decimals: 1,234,567.99'
user tuple elements and complex datatypes
>>> date = (9, 6, 2023)
>>> f"Date: {date[0]:02}-{date[1]:02}-{date[2]}"
'Date: 09-06-2023'
>>> from datetime import datetime
>>> date = datetime(2023, 9, 26)
>>> f"Date: {date:%m/%d/%Y}"
'Date: 09/26/2023'
A typical use case of using different quotation marks in an f-string is when you need to use an apostrophe or access a dictionary key in an embedded expression:
>>> person = {"name": "Jane", "age": 25}
>>> f"Hello, {person['name']}! You're {person['age']} years old."
"Hello, Jane! You're 25 years old."
Here are some best practices when using f-strings in Python:
Hopefully if you haven't used fstrings yet, this will help you get started.