How To Print Variables In Python?

Python is a very versatile programming language that provides a lot of different methods in order to print variables and strings in different ways. Mainly the print() statement is used to print provided variables by using extra operators like %, {} , + , f-string, comma etc.

print() Statement

The print() statement is used to print variables and values by converting them into strings. The print() statement accepts different parameters and the syntax of the print() statement is like below.

print(VALUE,VARIABLE,...)
  • VALUE and VARIABLE are used to print strings by joining them with different methods.

In the following example, we print a simple string to the standard output.

print("Hello Pythontect")

Print Multiple Variables with , Operator

The , command operator is used to printing multiple variables by providing them into print() statement as parameters. The variables are joined and printed as a single string.

name = "Pythontect"
number=123

print("Hello ",name,number)
Hello  Pythontect 123

We can also print string values besides the variables like below by using the print() statement.

name = "Pythontect"
number=123

print("Hello ",name,number,"456")
Hello  Pythontect 123 456

Format and Print Variable with % Operator

Another way to print variables is using the % percentage operator with the print() method. The % operator is used to customize the string format like settings adjusting, padding, alignment, set precision, width, etc. We can put multiple variables inside a tuple and provide them to the print() statement in a formatted way. %s is used to represent string variables, %d is used to represent integer variables.

name = "Pythontect"
number=123

print("Hello %s %d",name,number)

Format and Print Variable with {} Operator

The {} operator is used to take place for the provided variables in a formatted way. The {} is used with the format() function of a string. The variables are provided to the format() method and put into the string by replacing the {} operator.

name = "Pythontect"
number=123

print("Hello {} {}".format(name,number))

Print Variables Joining with + Operator

The +plus operator is used to concatenate string values and variables into a single one. The + operator can be used to print multiple variables as strings. But be aware that non-string variables like integer, list, etc. should be converted into string with the str() function before concatenation.

name = "Pythontect"
number=123

print("Hello "+name+" "+str(number))

Print Variables with f-string

The f-string is used to print variables by putting variable names inside the string by surrounding them with curly brackets {VARIABLE_NAME} .

name = "Pythontect"
number=123

print(f"Hello {name} {number}")

Leave a Comment