Introduction
Printing something in Python is pretty straightforward. There is a built-in function called 'print' for it. Let's take an example.
Examples
print("This is the Print Function")
Output
This is the Print Function
Escape Sequence
In python, you can use an escape character or backslash(\) to avoid the illegal characters in a string. Let's try to print an illegal string and see what happens.
Example 1
print('It's My first Python Program')
Output
File "/home/suvankar/Desktop/sample_code.py", line 3
print('It's My first Python Program')
^
SyntaxError: invalid syntax
Example 2
The solution to the above problem is to put an escape character before the illegal character in that string.
print('It\'s My first Python Program')
Output
It's My first Python Program
Example 3
Here is an another example for printing unlawful string.
# "hosts" is an illegal format in the string
# But avoid those double quotes by putting \ character
# before it.
print("Every Operating System has a \"hosts\" file.")
Output
Every Operating System has a "hosts" file.
Raw Strings in Python
In python, you can print a raw string by putting 'r' before it. It'll treat all the backslashes(\) as a literal character. So it will be helpful when you'll try to print a string that contains so many backslashes; for example, the location of a file or a directory in windows.
# Put 'r' before the quotation
print(r"C:\Windows\System32\drivers\etc\hosts")
Output
C:\Windows\System32\drivers\etc\hosts
Print New Lines in Python
print("1. First Line\n2. Second Line\n3. Third Line")
Output
1. First Line
2. Second Line
3. Third Line
Concatenates two Strings and Print the Final Result
# Concatenate two Strings
print("Welcome to" + " PySeek")
Output
Welcome to PySeek
Arithmetic in the Print Function
You can perform arithmetic operations in the print function too. Below the example is for you.
# Sum of two numbers
print("Result 1: ",5+2)
# Multiplication
print("Result 2: ",30*0.08)
# Division
print("Result 3: ",90-2)
Output
Result 1: 7
Result 2: 2.4
Result 3: 88