Python – Print string to console output
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.
1. Print a string value to console
The following is a basic example, where we print the string Hello World to console.
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.
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.
We have overridden the default separator with a character. You can also use a string for a separator.
Hello, - World
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.
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.