F strings in Python - How to use Them?

in Python5 months ago

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.

Here are some fstring examples

>>> name = "Jane"
>>> age = 25

>>> f"Hello, {name}! You're {age} years old."
'Hello, Jane! You're 25 years old.'

put your expressions right into your f-strings

>>> f"{2 * 21}"
'42'

user various format specifiers:

>>> 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'

Quotations and Quotes

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."

Tips for use

Here are some best practices when using f-strings in Python:

  • Use f-strings for simple string interpolation: F-strings are ideal for simple string interpolation where you need to include variables or expressions inside a string. Their syntax is straightforward and easy to read
  • Keep expressions simple: While f-strings allow complex expressions, keep them simple for readability. Complex expressions can make your code harder to understand 1.
  • Consider performance: f-strings are faster than traditional string formatting methods so can help with application performance
  • Use f-strings for debugging: F-strings can be very useful for debugging due to their self-documenting expressions. By using a variable name followed by an equal sign (=) in an f-string, you can display the variable's name, the equal sign, and the variable's current value 1.
  • Avoid unnecessary complexity: While f-strings offer many powerful features, avoid unnecessary complexity. Sometimes, traditional string formatting tools might be simpler and more suitable for certain scenarios.

Hopefully if you haven't used fstrings yet, this will help you get started.

Sort:  

Congratulations @agileautomation! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You received more than 50 upvotes.
Your next target is to reach 100 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP