Python print() function
print() function
The print() function is a fundamental part of Python that allows for easy console output. The function has replaced the older print statement in Python 3, providing more versatility with keyword arguments. This tutorial explains various ways to use print() for different formatting needs, string manipulation, and data types.
The simplest way to use the print() function is by passing a string or variable as an argument:
- print("Good Morning")
- print("Good", <Variable Containing the String>)
- print("Good" + <Variable Containing the String>)
- print("Good %s" % <variable containing the string>)
Syntax and Parameters
The general syntax for print() is:
print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Parameters:
- sep: Specifies the separator between values. Default is a single space.
- end: Specifies the string to be appended at the end of the output. Default is a newline.
- file: Defines the output destination. Default is sys.stdout. Use sys.stderr for errors.
- flush: If True, forcibly flushes the output buffer.
Examples with sep and end:
print("Python", "is", "fun", sep="-") # Output: Python-is-fun
print("Hello", end=", ")
print("world!") # Output: Hello, world!
1. Advanced String Formatting
Python provides multiple ways to format strings in print().
Using F-Strings (Python 3.6+):
F-strings provide an efficient way to embed expressions within string literals.
name = "Tom"
age = 25
print(f"Hello, {name}. You are {age} years old.")
Output:
Hello, Tom. You are 25 years old.
2. Using .format()
The .format() method is versatile and allows you to format strings with placeholders.
name = "Tom"
age = 25
print("Hello, {}. You are {} years old.".format(name, age))
Output:
Hello, Tom. You are 25 years old.
3. Using % Operator
The % operator is an older method that remains useful for specific formatting needs.
name = "Tom"
age = 25
print("Hello, %s. You are %d years old." % (name, age))
Output:
Hello, Tom. You are 25 years old.
Working with Quotes in Strings
- Single Quotes: For simple strings: print('Hello')
- Double Quotes: Useful for strings with single quotes inside: print("Python's simplicity")
- Triple Quotes: Allow multi-line strings and embedded quotes
print("""Python is versatile.
It's also popular!""")
Variable Use:
Strings can be assigned to variable say string1 and string2 which can called when using the print statement.
Example-1:
str1 = 'Wel'
print(str1,'come')
Output:
Wel come
Example-2:
str1 = 'Welcome'
str2 = 'Python'
print(str1, str2)
Output:
Welcome Python
String Concatenation:
String concatenation is the "addition" of two strings. Observe that while concatenating there will be no space between the strings.
Example:
str1 = 'Python'
str2 = ':'
print('Welcome' + str1 + str2)
Output:
WelcomePython:
Using as String:
%s is used to refer to a variable which contains a string.
Example:
str1 = 'Python'
print("Welcome %s" % str1)
Output:
Welcome Python
Using other data types:
Similarly, when using other data types
- %d -> Integer
- %e -> exponential
- %f -> Float
- %o -> Octal
- %x -> Hexadecimal
This can be used for conversions inside the print statement itself.
Using as Integer:
Example:
print("Actual Number = %d" %15)
Output:
Actual Number = 15
Using as Exponential:
Example:
print("Exponential equivalent of the number = %e" %15)
Output:
Exponential equivalent of the number = 1.500000e+01
Using as Float:
Example:
print("Float of the number = %f" %15)
Output:
Float of the number = 15.000000
Using as Octal:
Example:
print("Octal equivalent of the number = %o" %15)
Output:
Octal equivalent of the number = 17
Using as Hexadecimal:
Example:
print("Hexadecimal equivalent of the number = %x" %15)
Output:
Hexadecimal equivalent of the number = f
Using multiple variables:
When referring to multiple variables parenthesis is used.
Example:
str1 = 'World'
str2 = ':'
print("Python %s %s" %(str1,str2))
Output:
Python World :
Repeating Characters
Use multiplication with strings to repeat characters:
print('#' * 10) # Output: ##########
Other Examples of Print Statement:
The following are other different ways the print statement can be put to use.
Example - % is used for %d type
% is used for %d type word
print("Welcome to %%Python %s" %'language')
Output:
Welcome to %Python language
Example - Line Break
\n is used for Line Break.
print("Sunday\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday")
Output:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Example - multiple times
Any word print multiple times.
print('-w3r'*5)
Output:
-w3r-w3r-w3r-w3r-w3r
Example - using tab
\t is used for tab.
print("""
Language:
\t1 Python
\t2 Java\n\t3 JavaScript
""")
Output:
Language: 1 Python 2 Java 3 JavaScript
Precision width and field width:
Field width is the width of the entire number and precision is the width towards the right. One can alter these widths based on the requirements.
The default Precision Width is set to 6.
Example - decimal points
Notice upto 6 decimal points are returned. To specify the number of decimal points, '%(fieldwidth).(precisionwidth)f' is used.
print("%f" % 5.1234567890)
Output:
5.123457
Example - decimal points
Notice upto 5 decimal points are returned
print("%.5f" % 5.1234567890)
Output:
5.12346
Example - field width is set more than the necessary
If the field width is set more than the necessary than the data right aligns itself to adjust to the specified values.
print("%9.5f" % 5.1234567890)
Output:
5.12346
Example - Zero padding
Zero padding is done by adding a 0 at the start of fieldwidth.
print("%015.5f" % 5.1234567890)
Output:
000000005.12346
Example - proper alignment
For proper alignment, a space can be left blank in the field width so that when a negative number is used, proper alignment is maintained.
print("% 9f" % 5.1234567890)
print("% 9f" % -5.1234567890)
Output:
5.123457 -5.123457
Example - adding a + sign
'+' sign can be returned at the beginning of a positive number by adding a + sign at the beginning of the field width.
print("%+9f" % 5.1234567890)
print("% 9f" % -5.1234567890)
Output:
+5.123457 -5.123457
Example - specifying a negative symbol
As mentioned above, the data right aligns itself when the field width mentioned is larger than the actually field width. But left alignment can be done by specifying a negative symbol in the field width.
print("%-9.4f" % 5.1234567890)
Output:
5.1235Pretty Printing with pprint
For structured data, such as dictionaries, use the pprint module to print data in a readable format.
from pprint import pprint
data = {"Python": 3, "Java": 8, "C++": 11}
pprint(data)
Output:
{'C++': 11, 'Java': 8, 'Python': 3}
Test your Python skills with w3resource's quiz
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics