Print variable in Python like a PRO [SOLVED]


Written By - admin
Advertisement

Different methods to print variable in Python

In this tutorial you will learn about how you can declare and print variables in python using multiple methods. Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The handling of variable is different with Python so if you wish to print text with variable then you need to use proper syntax with print () function.

There are several ways to print a variable in Python:

  1. Using the print() function: print(my_variable)
  2. Using string concatenation: print("My variable is: " + str(my_variable))
  3. Using the format() method: print("My variable is: {}".format(my_variable))
  4. Using f-strings (introduced in Python 3.6): print(f"My variable is: {my_variable}")
  5. Using the % operator (also known as the string formatting operator): print("My variable is: %d" % my_variable)
  6. Using the logging module
  7. Using the pprint() function from the pprint module to pretty-print the variable.

 

How to print variable with string values

In this section we will cover different examples to print a variable which contains a string:

 

Example-1: Using the print() function

my_variable = "Hello World"
print("The variable contains: " + my_variable)

 

Example-2: Using string concatenation

  • Ideally + character is used for mathematical operations but you can also use + to join to variables
  • Additionally we would need str() function to convert the input value to string to be able to print variables using this method
  • Because by default + would consider var1 as integer here and fail to concatenate since var2 and var3 are strings
my_variable = "Hello World"
print("The variable contains: " + my_variable)

 

Example-3: Using the format() method

  • Format Specifications can also be used as replacement fields contained within a format string to define how individual values are presented
  • Starting with python version 3.1 the positional argument specifiers can be omitted for str.format(), so '{} {}'.format(a, b) is equivalent to '{0} {1}'.format(a, b).
my_variable = "Hello World"
print("The variable contains: {}".format(my_variable))
  • Format Specifications can also be used as replacement fields contained within a format string to define how individual values are presented
  • Starting with python version 3.1 the positional argument specifiers can be omitted for str.format(), so '{} {}'.format(a, b) is equivalent to '{0} {1}'.format(a, b).
print("I have {} students: {} and {}".format(var1,var2,var3))

To access arguments using position

print("I have {0} students: {1} and {2}".format(var1,var2,var3))

You can change the positional argument sequence and accordingly it would take the values from str.format()

print("I have {2} students: {1} and {0}".format(var3,var2,var1))

Output:

I have 2 students: deepak and amit

 

Example-4: Using f-strings

This method was introduced in Python 3.6 and is not available in older releases.

  • You embed variables inside a string by using a special {} sequence and then put the variable you want inside the {} characters.
  • You also must start the string with the letter f for “format,” as in f"Hello {somevar}".
  • This little f before the " (double-quote) and the {} characters tell "Hey, this string needs to be formatted. Put these variables in there."
my_variable = "Hello World"
print(f"The variable contains: {my_variable}")

 

Example-5: Using % (string formatting) operator

my_variable = "Hello World"
print("The variable contains: %s" % my_variable)

 

How to print variables with integer values

Here are some examples where we will print variables containing values as integers:

Advertisement
first_number = 5
second_number = 10

# Using string concatenation
print("The sum of " + str(first_number) + " and " + str(second_number) + " is " + str(first_number + second_number))

# Using the format() method
print("The sum of {} and {} is {}".format(first_number, second_number, first_number + second_number))

# Using f-strings (introduced in Python 3.6)
print(f"The sum of {first_number} and {second_number} is {first_number + second_number}")

# Using the % operator
print("The sum of %d and %d is %d" % (first_number, second_number, first_number + second_number))

The first method, using string concatenation, combines a series of strings and variables using the + operator. The str() function is used to convert the integer values of first_number and second_number to strings so that they can be concatenated with the other strings.

The second method, using the format() method, uses placeholders in the form of curly braces {} in the string, which are replaced with the values of the variables when the format() method is called.

The third method, using f-strings, is also similar to the format() method, but it uses a slightly different syntax. It uses curly braces {} to enclose the variable names, and the values are filled in when the string is executed.

The fourth method, using the % operator, uses %d to format the string.

 

How to print variables with float values

Let's also check some examples to print variables contains floating values:

first_number = 5.5
second_number = 10.2

# Using string concatenation
print("The sum of " + str(first_number) + " and " + str(second_number) + " is " + str(first_number + second_number))

# Using the format() method
print("The sum of {:.2f} and {:.2f} is {:.2f}".format(first_number, second_number, first_number + second_number))

# Using f-strings (introduced in Python 3.6)
print(f"The sum of {first_number:.2f} and {second_number:.2f} is {first_number + second_number:.2f}")

# Using the % operator
print("The sum of %.2f and %.2f is %.2f" % (first_number, second_number, first_number + second_number))

The first method, using string concatenation, combines a series of strings and variables using the + operator. The str() function is used to convert the float values of first_number and second_number to strings so that they can be concatenated with the other strings.

The second method, using the format() method, uses placeholders in the form of curly braces {:.2f} in the string, which are replaced with the values of the variables when the format() method is called. The :.2f is used to format the float value to two decimal places, this means that only two decimal places will be printed.

The third method, using f-strings, is also similar to the format() method, but it uses a slightly different syntax. It uses curly braces {} to enclose the variable names, and the values are filled in when the string is executed. The :.2f is used to format the float value to two decimal places, this means that only two decimal places will be printed.

Advertisement

The fourth method, using the % operator, uses %.2f to format the string, it uses the same syntax as in C. The .2f is used to format the float value to two decimal places, this means that only two decimal places will be printed.

 

How to print variables with decimal values

Here are some examples to print python variables having decimal values:

from decimal import Decimal

first_number = Decimal('5.5')
second_number = Decimal('10.2')

# Using string concatenation
print("The sum of " + str(first_number) + " and " + str(second_number) + " is " + str(first_number + second_number))

# Using the format() method
print("The sum of {} and {} is {}".format(first_number, second_number, first_number + second_number))

# Using f-strings (introduced in Python 3.6)
print(f"The sum of {first_number} and {second_number} is {first_number + second_number}")

The first method, using string concatenation, combines a series of strings and variables using the + operator. The str() function is used to convert the decimal values of first_number and second_number to strings so that they can be concatenated with the other strings.

The second method, using the format() method, uses placeholders in the form of curly braces {} in the string, which are replaced with the values of the variables when the format() method is called.

The third method, using f-strings, is also similar to the format() method, but it uses a slightly different syntax. It uses curly braces {} to enclose the variable names, and the values are filled in when the string is executed.

 

Print and concatenate variables of different types

In this example, there are three variables defined: name, age, and location. Each of these variables is then used in a string that is printed to the console using a different method.

Advertisement
name = "Amit"
age = 30
location = "India"

# Using string concatenation
print("My name is " + name + ", I am " + str(age) + " years old and I live in " + location)

# Using the format() method
print("My name is {}, I am {} years old and I live in {}".format(name, age, location))

# Using f-strings (introduced in Python 3.6)
print(f"My name is {name}, I am {age} years old and I live in {location}")

# Using the % operator
print("My name is %s, I am %d years old and I live in %s" % (name, age, location))

The first method, using string concatenation, combines a series of strings and variables using the + operator. The str() function is used to convert the integer value of age to a string so that it can be concatenated with the other strings.

The second method, using the format() method, uses placeholders in the form of curly braces {} in the string, which are replaced with the values of the variables when the format() method is called.

The third method, using f-strings, is also similar to the format() method, but it uses a slightly different syntax. It uses curly braces {} to enclose the variable names, and the values are filled in when the string is executed.

The fourth method, using the % operator, uses %s, %d, %i to format the string, it uses the same syntax as in C.

 

Conclusion

In this tutorial we learned how to print variables with python using different possible methods. You can choose the preferred method based on your requirement. Python programming language defines variable differently compared to other language such as bash and perl. In shell script and perl we call a variable by appending dollar sign $ to the variable name but that is not the case with python.

Lastly I hope the steps from the article to declare and print variable in Python was helpful. So, let me know your suggestions and feedback using the comment section.

 

References

Python print function

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

1 thought on “Print variable in Python like a PRO [SOLVED]”

Leave a Comment