. Advertisement .
..3..
. Advertisement .
..4..
Printing different values in Python is not a very challenging task. However, printing a variable in Python is a bit different. In this blog, we will discuss some of the methods of printing a variable in Python. Read on.
How Can You Print Variable in Python?
Option 1: Print single variable
Use this approach if you only want to print a single variable. Let’s take a look at an example:
var1 = "Hello guys"
print(var1)
Result:
Hello guys.
Option 2: Print multiple variables
All Python versions support the print statement, but the syntax differs according to Python version.
var1 = "Hello guys"
var2 = "how are you"
print(var1,var2)
Result:
Hello guys how are you
Option 3: Utilize comma character
Using a comma character to split the variables in a print statement is the simplest way to print a variable in Python.
var1 = 2
var2 = 'harry'
var3 = 'carry'
print("I have", var1, "bestfriends:", var2, "and", var3)
Result:
I have 2 bestfriends: harry and carry.
Option 4: Utilize %
You can also print a multiple variable by utilizing %
as the following:
var1 = 1
var2 = "harry" print("I have only %d bestfriend and he is %s" %(var1,var2))
Result:
I have only 1 bestfriend and he is harry
Option 5: Utilize f-string
Another approach to formatting strings is the f-string
, which has an advantage over the other two approaches due to its relative speed. Let’s take a look at an example:
var1= "How are you"
var2= "whts up"
print(f'Hello guys {var1} {var2}')
Result:
Hello guys How are you whts up
Option 6: Utilize {}
In order to indicate where the variable has to be substituted in a statement while using string formatting, you can use {}
symbol. String formatting is used in the Python code that prints the variable and string on the same line. Let’s look at the following example:
var1= 123
var2= 'World'
print("Hello to the {} {}".format(var2,var1))
Output:
Hello to the World 123
Option 7: Utilize + operator
When utilizing the print statement, the variables can also be separated using the +
operator. For instance:
var1= 123
var2= 'World'
print('Hello to the {} {}' + var2 + str(var1))
Output:
Hello to the World 123
Conclusion
We hope you enjoyed our blog about ” Tips on printing variable in Python”. If you have any other questions or concerns about this issue, please leave a comment below. Thank you for reading, we are always excited when one of our posts can provide useful information on a topic like this!
This article is also helpful for you to read. Let’s read it to get more information.
Read more
→ Tips On Examining Whether a Variable Is None Variable in Python
Leave a comment