Movatterモバイル変換


[0]ホーム

URL:


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

Want to code faster? OurPython Code Generator lets you create Python scripts with just a few clicks. Try it now!

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 valuename = "Abdou"age = 24print(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 "=" signprint(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 ♥

Want to code smarter? OurPython Code Assistant is waiting to help you. Try it now!

View Full Code Explain My Code
Sharing is caring!



Read Also


How to Split a String In Python
How to Organize Files by Extension in Python
Logging in Python

Comment panel

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





    Ethical Hacking with Python EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Ethical Hacking with Python EBook - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Practical Python PDF Processing Chapter.

    See how the book can help you build handy PDF Processing tools!



    [8]ページ先頭

    ©2009-2025 Movatter.jp