How to print variables in Python?


In this blog post, we will be discussing how to print variables in Python. We will cover six different ways to do this.

You can print a Python variable with the print Statement.

The print statement is probably the most basic way to print a variable in Python. All you need to do is type print(variable_name) and the variable will be printed.

print(variable_name)
Code language: PHP (php)

You can also use a comma (,) to separate the variables and print them. For example, if you want to print two variables, you can do it like this:

print(variable_1, variable_2).
Code language: PHP (php)

Example code:

#Python 3 code print('Hello World!!!') #Output: Hello World!!! print('Hello', "John") #Output: Hello John
Code language: Python (python)

Use String Formatting with the help of %

Another way to print variables is by using string formatting with the help of %. For example, if you have a variable x that you want to insert into a string, you can do it like this:

x = 5 print("The value of x is %d" %x) # Output: The value of x is 5 print("Hi, my name is %s" % "Marry") #Output: Hi, my name is Marry
Code language: Python (python)

String formatting with {}

String formatting with {} is another way to insert variables into strings. For example, if you want to insert a variable y into a string, you can do it like this:

y = 9 print("The value of y is {}".format(y)) #Output: The value of y is 9
Code language: Python (python)
int_var = 12345 str_var = 'World' print("Hello to the {} {}".format(str_var, int_var)) # Output: Hello to the World 12345
Code language: Python (python)

Using the + operator

You can also use the + operator to separate variables in the print statement. For example, if you want to concatenate two strings, you can do it like this:

print("Hello" + "World").
Code language: PHP (php)
int_var1= 1234 str_var2= 'World' print('Hello to the {} {}' + str_var2 + str(int_var1)) #Output: Hello to the World 1234
Code language: PHP (php)

Using f-strings in the print statement

If you’re using Python 3.6 or higher, you can also use f-strings in the print statement. F-strings are basically a shorthand way of writing formatted strings. For example, if you want to concatenate two strings, you can do it like this:

print(f"Hello {string_1} {string_2}").
Code language: PHP (php)
var1= 333 var2= 'World' print(f'Hello to the {var2} {var1}') #Output: Hello to the World 333
Code language: PHP (php)

Conclusion:

As we have seen, there are many ways to print variables in Python. Which method you choose depends on your specific needs and preferences. However, all of these methods are equally valid and should work without any problems.

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts