- Printing To Console In Python
- Console output in Python:
- Example:
- Python String formatting and printing:
- Method1: Format using repr() and string concatenation operator:
- Example:
- Method2: Use the format method on string object:
- Method3: C style printf like formating:
- Python Concepts/Console Output
- Lesson [ edit | edit source ]
- Writing to standard output [ edit | edit source ]
- Writing to standard error [ edit | edit source ]
- Output streams redirected [ edit | edit source ]
- Overriding output redirection [ edit | edit source ]
- Assignments [ edit | edit source ]
- Further Reading or Review [ edit | edit source ]
- References [ edit | edit source ]
- Print String to Console Output in Python
- Syntax of print()
- Examples
- 1. Print a string value to console
- 2. Print multiple values to console
- 3. Print with separator
- 4. Print with different ending character
- Summary
- print() Built-in Function
- Syntax of print()
- Examples
- 1. Print string to console
- 2. Print number to console
- 3. Print variables to console
- 4. print() with a specific separator between values
- 5. Print with a specific end value
- Video Tutorial
- Summary
Printing To Console In Python
Console Input/Output output is most important as it acts as the basic text based interface
for the python programs. Almost all of us who learn programming start with writing a
program that prints to the screen — «Hello World».
Console output in Python:
The built-in function print() of Python, prints any string passed to it to the screen.
Example:
The above example prints the string ‘Hello python world’ to the console.
How to print integers and floating point numbers using print method?
The following sections present multiple ways to print basic python types to the console,
using the print method.
Python String formatting and printing:
Method1: Format using repr() and string concatenation operator:
a) Convert any type to string
b) Append the newly formed string with the use of string concatenation operator
Example:
Temperature = 80.5
print(‘Temperature today is ‘+repr(Temperature)+’ Fahrenheit’)
The repr() function provides the string format of any type. The String Concatenation +
appends this string to the main string to be printed.
In the above example, converting the floating point to string representation and
concatenating is all done by the programmer.
Method2: Use the format method on string object:
Another way is to use the format method and the format fields available in python.
The other values like integer and floating point numbers can be placed in
the string by using the format field <>. The format method has to be called on that
string by passing the value to printed.
Temperature = 79.5
print(‘Temperature today is <> Fahrenheit’.format(Temperature))
Method3: C style printf like formating:
For die-hard c fans, the old style or c style formatting is still supported.
Where different format specifiers can be used with %.
Temperature = 78.5
print(‘Temperature today is %f Fahrenheit’,%(Temperature))
Python Concepts/Console Output
This lesson on Console I/O contains material specific to Python running directly from a Unix/Linux shell. It does not apply to Python running under Windows or under popular IDEs such as IDLE or PyCharm. Many of the examples will fail in various ways under Windows or with IDEs.
Lesson [ edit | edit source ]
In the context of this lesson, the word «console» implies the visual display which you see in front of you when you sit at your desk, and also the keyboard. The visual display provides console output and the keyboard provides «console input.»
The simplest way to write to the console or visual display is python’s print function.
print ('Hello, world!') # Contents of python script t4.py
$ python3.6 t4.py # Execute the python script. Hello, world! $
When the print statement in the script was executed, the string ‘Hello, world!’ appeared on the visual display in front of us. In technical terms the string was written to standard output, usually the console.
Python reserves two file objects for console output: standard output and standard error:
>>> import sys >>> sys.stdout _io.TextIOWrapper name='' mode='w' encoding='UTF-8'> >>> sys.stderr _io.TextIOWrapper name='' mode='w' encoding='UTF-8'> >>> >>> import io >>> isinstance(sys.stdout, io.TextIOWrapper) True >>> isinstance(sys.stderr, io.TextIOWrapper) True >>>
Both of the above file objects are always open for writing in text mode. Each of the file objects has its associated file descriptor:
>>> sys.stdout.fileno() 1 >>> sys.stderr.fileno() 2
File descriptor 1 usually means standard output, file descriptor 2 usually means standard error. When you write to stdout or stderr, the data written usually appears on the visual display in front of you unless their outputs are redirected.
Writing to standard output [ edit | edit source ]
import sys import os print ('line 1 to stdout ') sys.stdout.write('line 2 to stdout ') os.write(1, b'line 3 to stdout ')
$ python3.6 t4.py line 1 to stdout line 3 to stdout line 2 to stdout $
Line 3 was printed before line 2. To produce the expected result flush the buffer as necessary.
import sys import os print ('line 1 to stdout ') sys.stdout.write('line 2 to stdout ') ; sys.stdout.flush() os.write(1, b'line 3 to stdout ')
$ python3.6 t4.py line 1 to stdout line 2 to stdout line 3 to stdout $
To produce acceptable output add the newline at the end of each line as necessary:
import sys import os print ('line 1 to stdout ') sys.stdout.write('line 2 to stdout \n') ; sys.stdout.flush() os.write(1, b'line 3 to stdout \n')
$ python3.6 t4.py line 1 to stdout line 2 to stdout line 3 to stdout $
Writing to standard error [ edit | edit source ]
import sys import os print (' line 1e to stderr ', file=sys.stderr) sys.stderr.write(' line 2e to stderr \n') ; sys.stderr.flush() os.write(2, b' line 3e to stderr \n')
$ python3.6 t4.py line 1e to stderr line 2e to stderr line 3e to stderr $ python3.6 t4.py 2>/dev/null # Standard error redirected. $ # No output to console.
Output streams redirected [ edit | edit source ]
import sys import os print (' line 1 to stdout ') sys.stdout.write(' line 2 to stdout \n') ; sys.stdout.flush() os.write(1, b' line 3 to stdout \n') print (' line 1e to stderr ', file=sys.stderr) sys.stderr.write(' line 2e to stderr \n') ; sys.stderr.flush() os.write(2, b' line 3e to stderr \n')
$ python3.6 t4.py # No output redirection line 1 to stdout # All output appears on the console. line 2 to stdout line 3 to stdout line 1e to stderr line 2e to stderr line 3e to stderr $ python3.6 t4.py 1>/dev/null # stdout redirected line 1e to stderr # Only stderr appears on console. line 2e to stderr line 3e to stderr $ python3.6 t4.py 2>/dev/null # stderr redirected line 1 to stdout # Only stdout appears on console. line 2 to stdout line 3 to stdout $ python3.6 t4.py 1>/dev/null 2>/dev/null # Both streams redirected. $ # No output to console. $ $ python3.6 t4.py >/dev/null # If no fd is specified, default is 1. line 1e to stderr line 2e to stderr line 3e to stderr $
Overriding output redirection [ edit | edit source ]
If you wish to override output redirection so that some output goes to the terminal unconditionally, here is one way to do it:
import sys import os print ('hello, world!') # file=sys.stdout is default print ('Hello, World!', file=sys.stderr) print ('Name of my terminal is:', os.ttyname(0)) f = open(os.ttyname(0), 'wt') print ('File object opened for output to my terminal is:', f) print ('line 1 written to terminal', file=f) f.close()
$ python3.6 t5.py # No output redirection. hello, world! Hello, World! Name of my terminal is: /dev/ttys003 File object opened for output to my terminal is: line 1 written to terminal $ $ python3.6 t5.py >sout 2>serr # File descriptors 1 and 2 redirected line 1 written to terminal # This output was not redirected. $ $ cat sout hello, world! Name of my terminal is: /dev/ttys003 File object opened for output to my terminal is: $ $ cat serr Hello, World! $
The above code makes the following assumption:
>>> os.ttyname(0) == os.ttyname(1) == os.ttyname(2) True >>>
If the above assumption is not valid:
>>> f1 = open(os.ttyname(1), 'wt') ; f1 # Device associated with stdout. _io.TextIOWrapper name='/dev/ttys002' mode='wt' encoding='UTF-8'> >>> f2 = open(os.ttyname(2), 'wt') ; f2 # Device associated with stderr. _io.TextIOWrapper name='/dev/ttys002' mode='wt' encoding='UTF-8'> >>>
Assignments [ edit | edit source ]
Further Reading or Review [ edit | edit source ]
References [ edit | edit source ]
29.1. sys — System-specific parameters and functions: «sys.stdout,» «sys.stderr,»
3. Python’s built-in functions:
Print String to Console Output in Python
Most often, we print data to console. Be it the result we want to display, or intermediate results that we want to check while debugging our program.
In this tutorial, we will learn how to print a string to console with some well detailed examples.
To print a string to console output, you can use Python built-in function – print().
Syntax of print()
The syntax of Python print() function is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- objects are comma separated objects that has to be printed to the file.
- sep is the separator used between objects. sep can be a string or a character. By default sep is space.
- end is the character or a string that has to appended after the objects.
- file is the place where our print function has to write the objects. By default it is sys.stdout, in other words system standard output which is console output.
If you would like to override the default values of sep, end, file or flush parameters, you can do so by giving the corresponding argument. We will see more about them in the following examples.
Examples
1. Print a string value to console
The following is a basic example, where we print the string Hello World to console.
Python Program
2. Print multiple values to console
You can also specify multiple strings separated by comma to the print function. All those strings will be considered as *objects parameter.
Python Program
In this example, we have provided two objects to the print() statement. Since the default separator is ‘ ‘ and the end character is new line, we got Hello and World printed with space between them and a new line after the objects.
3. Print with separator
Now, we will provide a separator to the print function.
Python Program
We have overridden the default separator with a character. You can also use a string for a separator.
Python Program
4. Print with different ending character
May be you do not want a new line ending. So, with print() function’s end parameter, you can specify your own end character or string when it prints to the console.
Python Program
Summary
In this tutorial of Python Examples, we learned how to print a string to console, how to specify a separator or ending to print() function, with the help of well detailed examples.
print() Built-in Function
To print strings to console or echo some data to console output, use Python inbuilt print() function.
print() function can take different type of values as argument(s), like string, integer, float, etc., or object of a class type.
The following is a simple demonstration of how to use print() function in a Python shell.
>>> print("Hello World! Welcome to Python Examples.") Hello World! Welcome to Python Examples. >>> print(10) 10
Syntax of print()
The syntax of print() function is
print(*objects, sep=' ', end='\n', file=None, flush=False)
Examples
1. Print string to console
In this example, we will print a string to console output. Pass string as argument to the print() function.
Python Program
Yeah! That one print statement is all of the program. Run it from your command prompt or terminal using python command. Or you can run it from your Jupyter Notebook.
The string is printed to the console as shown below.
2. Print number to console
In this example, we will pass integer (number) as argument to print() function and print the number to the console.
Python Program
Any datatype passed to the print function is implicitly converted to string and printed to the console. Hence, the int we passed as argument to print() is first converted to string, and then print to the console.
3. Print variables to console
You can provide multiple values to print() function as arguments. They will be printed to console with single space as a default separator. Again, you can specify your own separator, and we shall see that in our next example.
Python Program
Please note that space is printed out to console, between x and y.
4. print() with a specific separator between values
You can pass a string for named parameter sep to override the default separator.
Python Program
x = 'pi is' y = 3.14 print(x, y, sep=' : ')
x and y have been printed to the console with the specified separator.
5. Print with a specific end value
We already know that we can specify an ending value for print() function. New line character is the default ending for print() function in Python. You can override this by passing a string to the named parameter end as shown in the below Python program.
Python Program
print('Hello', end='-') print('World', end='.\n')
Video Tutorial
Summary
In this tutorial of Python Examples, we learned how to print a message to console, a variable or any other datatype to the console, using Python print() builtin function with the help of well detailed Python programs.