Python print variable with name

How to Print a Variable’s Name in Python?

In Python, a “variable” is used to reference an object in the program. A value given to a variable can be accessed using the variable’s name. The variable’s value can be printed in Python using the built-in print() function. However, printing the variable’s name is a bit tricky.

Different approaches are used in Python to print the variable’s name, such as the “globals()” function with list comprehension, Python dictionary, etc.

This post will provide a detailed guide on printing a variable name in Python using the following content:

Method 1: Using globals() Function

The “globals()” function is utilized along with a list comprehension method to print a variable name in Python. The globals() function retrieves the global symbol dictionary, which contains all the information related to the program. Let’s see how we can use this method to print a variable name in the below code:

int_variable = 456 int_variable1 = 46 print([name for name in globals() if globals()[name] == 456])
  • Two variables named “int_variable” and “int_variable1” are initialized in the program.
  • The list comprehension technique is used to iterate each item of the symbol dictionary.
  • A value is compared with the dictionary’s values. If the specified value matches any of the dictionary’s values, then the variable name in which that particular value is stored will be retrieved.
Читайте также:  Java url builder example

The output shows that the specified value “456” is stored in the “int_variable”.

Method 2: Using items() Method

The “items()” method is used along with the “locals()” function to print a variable name in Python. The “locals()” function returns the dictionary containing all the information related to the program in the local scope. The below example code is used to print variable names in Python:

int_variable = 76 int_variable1 = 76 print([name for name, i in locals().items() if i == 76])
  • The list comprehension method is used along with the “items()” function to iterate over each item and print the key that is similar to our variable value “76”.
  • The key here is the variable name that contains a similar variable value.

The above output shows that two variables contain the targeted value, i.e., “76”.

Note: Both locals() and globals() functions contain the necessary program information. One has information related to the local scope, and the other contains information related to the global scope. The below example demonstrates the comparative analysis of the locals() and globals() functions:

Code: Using locals() Function

int_variable = 76 def sample(): int_variable1 = 76 print([name for name, i in locals().items() if i == 76]) sample()

In the above code, the “local()” function is used along with “items()” function to check the specific variable value “76” inside the local scope and return the variable name.

The variable name “int_variable1,” having the value “76” and residing within the local scope, is displayed on the screen.

Code: Using globals() Function

int_variable = 76 def sample(): int_variable1 = 76 print([name for name in globals() if globals()[name] == 76]) sample()

In the above code, the “globals()” function is used with the list comprehension to check a specific value “76” at the global scope and return the variable name accordingly.

The globals() function retrieves the variable name with a value “76” declared at global scope.

Method 3: Using Python Dictionary

Users can manually create a dictionary that contains the variable value as a key and the variable’s name as a key’s value. Let’s understand via the following code:

val = 'Lily' val2 = 'Alex' name_variable = print(name_variable['Alex'])

In the above code, two variables named “val1” and “val2” are initialized at the start of the program. The dictionary named “name_variable” is created with a key containing the variable’s names as values. The key name is passed inside the square bracket to access the variable’s name.

The above output shows that “Alex” is stored in the “val2” variable.

Conclusion

To print variable names, “globals()”, “items()”, and “Python Dictionary” methods are used in Python. The “globals()” function with the list comprehension method prints a variable name in Python. The “items()” method is also used with the “locals()” function to print a variable name in Python. Moreover, we can also define our own dictionary to print the variable name in Python. This write-up presented a comprehensive guide on how to print a variable name in Python.

Источник

Python Print Variable – How to Print a String and Variable

Dionysia Lemonaki

Dionysia Lemonaki

Python Print Variable – How to Print a String and Variable

Python is a versatile and flexible language – there is often more than one way to achieve something.

In this tutorial, you’ll see some of the ways you can print a string and a variable together.

How to use the print() function in Python

To print anything in Python, you use the print() function – that is the print keyword followed by a set of opening and closing parentheses, () .

#how to print a string print("Hello world") #how to print an integer print(7) #how to print a variable #to just print the variable on its own include only the name of it fave_language = "Python" print(fave_language) #output #Hello world #7 #Python 

If you omit the parentheses, you’ll get an error:

print "hello world" #output after running the code: #File "/Users/dionysialemonaki/python_articles/demo.py", line 1 # print "hello world" # ^^^^^^^^^^^^^^^^^^^ #SyntaxError: Missing parentheses in call to 'print'. Did you mean print(. )? 

If you write your Python code in Visual Studio Code, with the Python extension, you’ll also get an underline and a hint which all indicate that something is not quite right:

Screenshot-2021-12-07-at-3.08.14-PM

As mentioned above, the print statement is used to output all kinds of information. This includes textual and numerical data,variables, and other data types.

You can also print text (or strings) combined with variables, all in one statement.

You’ll see some of the different ways to do this in the sections that follow.

How to print a variable and a string in Python using concatenation

To concatenate, according to the dictionary, means to link (things) together in a chain or series.

You do this by adding various things (in this case programming – you add data) together with one another, using the Python addition operator, + .

Keep in mind that concatenation is only used for strings, so if the variable you want to concatenate with the rest of the strings is of an integer data type, you’ll have to convert it to a string with the str() function.

In the following example, I want to print the value of a variable along with some other text.

I add the strings in double quotes and the variable name without any surrounding it, using the addition operator to chain them all together:

fave_language = "Python" print("I like coding in " + fave_language + " the most") #output #I like coding in Python the most 

With string concatenation, you have to add spaces by yourself, so if in the previous example I hadn’t included any spaces within the quotation marks the output would look like this:

fave_language = "Python" print("I like coding in" + fave_language + "the most") #output #I like coding inPythonthe most 

You can even add the spaces separately:

fave_language = "Python" print("I like coding in" + " " + fave_language + " " + "the most") #output #I like coding in Python the most 

This is not the most preferred way of printing strings and variables, as it can be error prone and time-consuming.

How to print a variable and a string in Python by separating each with a comma

You can print text alongside a variable, separated by commas, in one print statement.

first_name = "John" print("Hello",first_name) #output #Hello John 

In the example above, I first included some text I wanted to print in double quotation marks – in this case, the text was the string Hello .

After the closing quotation mark, I added a comma which separates that piece of text from the value held in the variable name ( first_name in this case) that I then included.

I could have added more text following the variable, like so:

first_name = "John" print("Hello",first_name,"good to see you") #output #Hello John good to see you 

This method also works with more than one variable:

first_name = "John" last_name = "Doe" print("Hello",first_name,last_name,"good to see you") #output Hello John Doe good to see you 

Make sure to separate everything with a comma.

So, you separate text from variables with a comma, but also variables from other variables, like shown above.

If the comma hadn’t been added between first_name and last_name , the code would’ve thrown an error:

first_name = "John" last_name = "Doe" print("Hello",first_name last_name,"good to see you") #output #File "/Users/dionysialemonaki/python_articles/demo.py", line 4 # print("Hello",first_name last_name,"good to see you") # ^^^^^^^^^^^^^^^^^^^^ #SyntaxError: invalid syntax. Perhaps you forgot a comma? 

As you see, Python error messages are extremely helpful and make the debugging process a bit easier 🙂

How to print a variable and a string in Python using string formatting

You use string formatting by including a set of opening and closing curly braces, <> , in the place where you want to add the value of a variable.

first_name = "John" print("Hello <>, hope you're well!") 

In this example there is one variable, first_name .

Inside the print statement there is a set of opening and closing double quotation marks with the text that needs to be printed.

Inside that, I’ve added a set of curly braces in the place where I want to add the value of the variable first_name .

If I try and run this code, it will have the following output:

#output #Hello <>, hope you're well! 

It doesn’t actually print the value of first_name !

To print it, I need to add the .format() string method at the end of the string – that is immediately after the closing quotation mark:

first_name = "John" print("Hello <>, hope you're well!".format(first_name)) #output #Hello John, hope you're well! 

When there is more than one variable, you use as many curly braces as the number of variables you want to print:

first_name = "John" last_name = "Doe" print("Hello <> <>, hope you're well!") 

In this example, I’ve created two variables and I want to print both, one after the other, so I added two sets of curly braces in the place where I want the variables to be substituted.

Now, when it comes to the .format() method, the order in which you place the variable names inside matters.

So, the value of the variable name that will be added first in the method will be in the place of the first curly brace, the value of the variable name that will be added second will be in the place of the second curly brace, and so on.

Make sure to separate the variable names by commas inside the method:

first_name = "John" last_name = "Doe" print("Hello <> <>, hope you're well!".format(first_name,last_name)) #output #Hello John Doe, hope you're well! 

If I’d reversed the order of the names inside the method, the output would look different:

first_name = "John" last_name = "Doe" print("Hello <> <>, hope you're well!".format(last_name,first_name)) #output #Hello Doe John, hope you're well! 

How to print a variable and a string in Python using f-strings

f-strings are a better and more readable and concise way of achieving string formatting compared to the method we saw in the previous section.

The syntax is easier and requires less manual work.

The general syntax for creating an f-string looks like this:

print(f"I want this text printed to the console!") #output #I want this text printed to the console! 

You first include the character f before the opening and closing quotation marks, inside the print() function.

To print a variable with a string in one line, you again include the character f in the same place – right before the quotation marks.

Then you add the text you want inside the quotation marks, and in the place where you want to add the value of a variable, you add a set of curly braces with the variable name inside them:

first_name = "John" print(f"Hello, !") #output #Hello, John! 

To print more than variable, you add another set of curly braces with the second variable name:

first_name = "John" last_name = "Doe" print(f"Hello, !") #output #Hello, John Doe! 

The order you place the variable names does matter, so make sure you add them according to the output you want.

If I had reversed the order of the names, I’d get the following output:

first_name = "John" last_name = "Doe" print(f"Hello, !") #output #Hello, Doe John! 

Conclusion

Thanks for reading and making it to the end! You now know a few different ways of printing strings and variables together in one line in Python.

If you want to learn more about Python, check out freeCodeCamp’s Python Certification.

It’s suitable for beginners as it starts from the fundamentals and gradually builds to more advanced concepts. You’ll also get to build five projects and put to practice all the new knowledge you acquire.

Источник

Оцените статью