Can you show more f-string examples?

0105

Sure! Here are a few more examples of using f-strings in Python:

Example 1: Basic Variable Insertion

age = 5
output = f"My dog is {age} years old."
print(output)

Output:

My dog is 5 years old.

Example 2: Mathematical Expressions

a = 10
b = 20
output = f"The sum of {a} and {b} is {a + b}."
print(output)

Output:

The sum of 10 and 20 is 30.

Example 3: Formatting Numbers

price = 49.99
output = f"The price is ${price:.2f}."
print(output)

Output:

The price is $49.99.

Example 4: Using Functions

def greet(name):
    return f"Hello, {name}!"

output = greet("Labby")
print(output)

Output:

Hello, Labby!

Example 5: Accessing Dictionary Values

person = {"name": "Alice", "age": 30}
output = f"{person['name']} is {person['age']} years old."
print(output)

Output:

Alice is 30 years old.

Feel free to ask if you need more examples or specific use cases!

0 Comments

no data
Be the first to share your comment!