__________     __ __     __  _______    ________
  / ____/ __ \   / // /    / / / /  _/ |  / / ____/
 / / __/ / / /  / // /_   / /_/ // / | | / / __/
/ /_/ / /_/ /  /__  __/  / __  // /  | |/ / /___
\____/\____/     /_/    /_/ /_/___/  |___/_____/

 --- A GOPHER-LIKE INTERFACE FOR HIVE BLOCKCHAIN ---

F strings in Python - How to use Them?

BY: @agileautomation | CREATED: Jan. 9, 2024, 11:09 p.m. | VOTES: 4 | PAYOUT: $0.00 | [ VOTE ]

https://snipboard.io/fH7cLS.jpg

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:

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

TAGS: [ #python ] [ #development ] [ #tips ] [ #fstrings ]

Replies

@hivebuzz | Jan. 10, 2024, 12:31 a.m. | Votes: 1 | [ VOTE ]

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

[ BACK TO TRENDING ] [ BACK TO MENU ]
CMD>