Can f-strings be used with dictionaries?

0320

Yes, f-strings can be used with dictionaries in Python. You can access dictionary values directly within the curly braces of an f-string.

Example:

person = {"name": "Alice", "age": 30}
greeting = f"My name is {person['name']} and I am {person['age']} years old."
print(greeting)  # Output: My name is Alice and I am 30 years old.

In this example, person['name'] and person['age'] retrieve the values from the dictionary, which are then embedded in the f-string. This makes it easy to format strings with data stored in dictionaries. If you have more questions, feel free to ask!

0 Comments

no data
Be the first to share your comment!