In Python version 3.9, f-strings (formatted string literals) have been improved to allow for more complex and flexible formatting options. Here are a few examples:
1. Using the `repr()` function inside an f-string:
# Define variables x, y, and z
x = [1, 2, 3] # x is a list of integers
y = "hello" # y is a string
z = True # z is a boolean value
# Use f-strings to print out the values of x, y, and z
print(f"The list is {repr(x)}") # prints 'The list is [1, 2, 3]' using the repr() function to display the list as a string
print(f"The string is {repr(y)}") # prints 'The string is "hello"' using the repr() function to display the string with quotation marks
print(f"The boolean is {repr(z)}") # prints 'The boolean is True' using the repr() function to display the boolean value as a string
2. Using the `format()` function inside an f-string:
# Define variables x and y
x = 10
y = 5
# Calculate average of x and y and format it to 2 decimal places
average = "{:.2f}".format((x + y) / 2)
# Print the average using an f-string
print(f"The average is {average}")
3. Using the `join()` function inside an f-string:
# Define a list of strings
words = ["apple", "banana", "cherry"]
# Define a delimiter to be used for joining the strings
delimiter = ", "
# Use the `join()` function to join the strings in the list using the delimiter
result = delimiter.join(words)
# Print the result using an f-string, adding a label for clarity
print(f"The fruits are: {result}") # prints 'The fruits are: apple, banana, cherry'
4. Using the `len()` function inside an f-string:
# Define a string variable
string = "hello world!"
# Use the len() function to get the length of the string
length = len(string)
# Print a formatted string using f-string, including the length of the string
print(f"This string has {length} characters.") # prints 'This string has 12 characters.'
5. Using the `max()` function inside an f-string:
# Creating a list of numbers
numbers = [3, 7, 1, 9]
# Finding the maximum number in the list using the max() function
max_num = max(numbers)
# Printing the result using an f-string
print(f"The largest number is {max_num}.") # prints 'The largest number is 9.'
6. Using the `min()` function inside an f-string:
# Using the `min()` function to find the smallest number in a list
numbers = [3, 7, 1, 9] # creates a list of numbers
min_num = min(numbers) # assigns the smallest number in the list to the variable min_num
# Printing the smallest number using an f-string
print(f"The smallest number is {min_num}.") # prints 'The smallest number is 1.' with the smallest number inserted into the string using the f-string format
# Output: The smallest number is 1.
These are just a few examples of the many ways you can use f-strings with formatted string literals in Python version 3.9 to make your code more concise and readable.