How to Print Variable Name and Value in Python

Learn the best way to print variable name and value in Python using F-strings.
  · 2 min read · Updated jan 2023 · Python Standard Library

Step up your coding game with AI-powered Code Explainer. Get insights like never before!

Python string formatting is a great tool to have in your toolbox. Python f-strings are updates on Python string formatting. It is faster at runtime, and it's easier to write. Once you start using it, there is no going back.

An f-string in Python is a string literal that is prefixed with the letter "f" and curly braces containing expressions that will be replaced with their values. They're a convenient and concise way to include the value of variables or expressions in a string, and they're especially helpful for quick debugging and logging purposes.

F-strings were introduced in Python 3.6 and are available in all subsequent versions. They provide a more readable alternative to the older .format() method for string formatting.

To create an f-string, you can prepend the string with the letter "f" and then include any Python variable within curly brackets:

# Normal way to print variable name and value
name = "Abdou"
age = 24
print(f"name: {name}, age: {age}")

Output:

name: Abdou, age: 24

However, there is a faster and even more convenient way to print the variable name and value using the "=" sign in f-strings:

# using the "=" sign
print(f"{name=}, {age=}")

Output:

name='Abdou', age=24

Remember that this syntax (using the "=" sign) is only available in Python 3.8 and above. If you're using an earlier version of Python, you must use the regular f-string method.

In conclusion, f-strings are a convenient and concise way to include the value of variables or expressions in a string in Python. They are especially useful for debugging or logging purposes, as they allow you to print the variable name and value in a single statement.

Learn also: How to Organize Files by Extension in Python.

Happy coding ♥

Save time and energy with our Python Code Generator. Why start from scratch when you can generate? Give it a try!

View Full Code Understand My Code
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!






    pFad - Phonifier reborn

    Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

    Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


    Alternative Proxies:

    Alternative Proxy

    pFad Proxy

    pFad v3 Proxy

    pFad v4 Proxy