Learn Python - Day 2
Print Methods
Print() function is used to print the output in console and also it has the ability to handle formatting, special characters, Unicode and so on. We will see it one by one with examples
1. Basic usage
It prints the given text or data to the console.
Example
print("Hello, World!")
Output
Hello, World!
2. Multiple Objects
It prints multiple objects with space as separator by default.
Example
print("Hello", "World")
Output
Hello World
3. Sep Parameter
We can override the default separator space by using the sep parameter.
Example
print("Hello", "World", sep=", ")
Here we used comma space as separator between the objects. Likewise we can use anything as separator.
Output
Hello, World
4. End Parameter
We can set what is printed at the end of the output using end parameter. It set as newline by default (\n).
Example
print("Hello, World", end="!")
print(" How are you?")
Here we changed the new line parameter into exclamatory symbol using end parameter, so that both print methods are printed as single line as show below.
Output
Hello, World! How are you?
5. Printing variable
It prints the value of the variables in console
Example
name = "Dinesh"
age = 25
print("Name:", name, "Age:", age)
Output
Name: Dinesh Age: 25
6. Formatted String Literals (f-strings)
We can include the expressions inside string literals using curly braces {}.
Example
age = 25
name = "Dinesh"
print(f"Name: {name}, Age: {age}")
Output
Dinesh, Age: 25
7. String Formatting with % Operator
Using % operator we can format the strings.
Example
name = "Dinesh"
age = 25
print("Name: %s, Age: %d" % (name, age))
Output
Name: Dinesh, Age: 25
8. String Formatting with str.format()
Uses the str.format() method to format strings.
Example
name = "Dinesh"
age = 25
print("Name: {}, Age: {}".format(name, age))
Name: Dinesh, Age: 25
9. Printing with File
Redirects the output to a file.
Example
with open("d:\\output.txt", "w") as file:
print("Hello, World!", file=file)
The text "Hello, world!" will write in txt file in the path "d:\output.txt"
10. Printing with Flush
Ensures the output is immediately flushed to the console.
Example
import time
for i in range(5):
print(i, end=' ', flush=True)
time.sleep(1)
Output
0 1 2 3 4
11. Printing Special Characters
Prints special characters like tab (\t), newline (\n), and backslash (\).
Example
print("Tab\tSpace")
print("New\nLine")
print("Backslash\\Example")
Output
Tab Space
New
Line
Backslash\Example