F-Strings - Advanced Python

F-strings, introduced in Python 3.6, are a way to format strings that is both concise and readable. An F-string is prefixed with `f` or `F` before the opening quotation mark. Within an F-string, you can directly insert expressions inside curly braces `{}`. The expressions are evaluated at runtime and formatted using Python's string formatting options.

Here's an overview and some examples:

Basic Usage

name = "Alice"

age = 30

 

greeting = f"Hello, my name is {name} and I am {age} years old."

print(greeting)

Expressions Inside Braces

You can place any valid Python expression inside the curly braces:

x = 10

y = 5

 

result = f"The result of {x} + {y} is {x + y}."

print(result)

Formatting Numbers

F-strings allow for inline formatting, which is handy for controlling the format of numbers:

import math

 

radius = 7.5

area = f"The area of a circle with a radius of {radius} is {math.pi * radius ** 2:.2f}."

print(area)

Here, `:.2f` formats the area to two decimal places.

Date and Time Formatting

F-strings can also be used to format dates and times:

from datetime import datetime

 

current_time = datetime.now()

formatted_time = f"Current time: {current_time:%Y-%m-%d %H:%M:%S}"

print(formatted_time)

Advanced Expressions

You can perform more complex operations inside the braces:

items = ['apples', 'bananas', 'grapes']

formatted_list = f"There are {len(items)} items: {', '.join(items).capitalize()}."

print(formatted_list)

This line creates a string using an f-string (formatted string literal). Inside this f-string, there are a couple of operations being performed on the items list:

  • len(items): This function returns the length of the list items, which is 3 in this case.
  • ', '.join(items): This method joins all the elements of the items list into a single string, separated by ', '. The result is 'apples, bananas, grapes'.
  • .capitalize(): This method is applied to the string resulting from the join operation. It capitalizes the first character of the string, turning it into 'Apples, bananas, grapes'.

F-strings are a powerful and efficient way to format strings in Python, making your code more readable and reducing the need for concatenation or manual string formatting.

Comments

Popular posts from this blog

cls in Functions

The Walrus Operator - Advanced Python

enumerate