Can I use other f-string features?

Yes, you can use several features with f-strings in Python! Here are some common ones:

  1. Expressions: You can include expressions inside the curly braces.

    books = 5
    print(f"I have {books * 2} books in total.")
  2. Formatting Numbers: You can format numbers directly within the f-string.

    price = 19.99
    print(f"The price is ${price:.2f}.")  # Outputs: The price is $19.99.
  3. Calling Functions: You can call functions inside the curly braces.

    def get_book_count():
        return 5
    print(f"I have {get_book_count()} books.")
  4. Using Dictionaries: You can access dictionary values.

    book_info = {'title': '1984', 'author': 'Orwell'}
    print(f"'{book_info['title']}' is written by {book_info['author']}.")
  5. Conditional Expressions: You can use conditional expressions.

    books = 5
    print(f"You {'have' if books > 0 else 'do not have'} books.")

These features make f-strings very powerful for creating dynamic and formatted strings. Feel free to explore these in your coding practice!

0 Comments

no data
Be the first to share your comment!