Python function: print() [ printing in Python ]

Signature

print(*objects, sep=' ', end='n', file=None, flush=False)

Parameters

Param NameDescriptionDefault Value
*objectsObjects to print, we can pass multiple objects.
sepSeparator between objects while printing‘ ‘ => single space character
endAdd this at the end of the outputn => new line
fileName of the file to print the string toNone
flushFlush the output immediately or notFalse

Notes

  • By default print function adds a new line at the end of the output, as the default value of the “end” parameter is “n”.

Usage

print function is used to print/output text on the screen or to a file. print() is a built-in function in Python.

Generally, we just pass a string as the first parameter, and the string literal is printed-

print('Welcome to BigBoxCode')

# Output: Welcome to BigBoxCode
Python

We can use single or double quotes to enclose the string literals, as both are allowed to represent strings in Python.

Examples

Here are some examples of Python “print” function usage. These examples demonstrate all possible usages of the Python print function.

Example #1: General string output

  • Pass a string to the print function and the function will print the string.
  • print() function will print a new line(n) character at the end of the output line. 
  • If we use the print() function with no parameter, then only a newline(n) will be printed.
print("First line of bigbox output")
print()
print()
print('Last line of bigbox output')
Python

Output

First line of bigbox output


Last line of bigbox output
Plaintext

Example #2: Multiline string with triple quote

  • We can use a triple quote(“””), at the beginning and end of the string to use this representation.
  • This string representation with triple quotes, includes the new lines in the result. So wherever we put a new line character in our string, we can see the new line in the result.
  • All the spaces and other special characters are kept as is, in this representation.
  • If we want to escape the new line in the result, then we can add a backslash() at the end of the line. This will not(escape) include the new lines that we put in our multiline string.
print(
    """This string is an example of
very long and multiline.
We are printing it to dmo the capability 
of representing a string with tripple quote.

We do not need to escape any quote
like a single quote ' or double quote "
These are escaped automatically."""
)

print(
    """In a multiline string 
in python, if we want to 
ignore the new line 
then we should use a backslash 
at the end of the line."""
)
Python

Output

This string is an example of
very long and multiline.
We are printing it to dmo the capability
of representing a string with tripple quote.

We do not need to escape any quote
like a single quote ' or double quote "
These are escaped automatically.
In a multiline string in python, if we want to ignore the new line then we should use a backslash at the end of the line.
Plaintext

Example #3: String concatenation

  • We can concatenate two(or more) strings inside the print function and pass as param.
  • We can also use variables and concatenate(if required) them with other strings, while passing them to the print function.
print("My concatenation example first part" + "My concatenation example second part")

name = "Charles Jackson"
message = "Welcome to the team"

print("Hello " + name + ", " + message)
Python

Output

My concatenation example first partMy concatenation example second part
Hello Charles Jackson, Welcome to the team
Plaintext

Example #4: Calculation

  • We can perform one or more calculations and pass that to the print() function as parameters.
print(4 + 6)
print(10 / 3)

print("Value of the calculation 4 + 6 is: ", (4 + 6))
Python

Output

10
3.3333333333333335
Value of the calculation 4 + 6 is:  10
Plaintext

Example #5: Multiple strings in the same print

  • We can pass two(or more) separate strings to print() function, as separate parameters by separating those with comma(,). 
  • This is allowed as the first parameter of print() function is “*objects”, which allows multiple parameters.
print("My first box", "My second box", "Third box here", "Fourth box")

print("Street:", "231 S High St")
print("City/Town:", "Baltimore")
print("State:", "Maryland")
print("ZipCode:", 21202)
print("Latitude:", 39.286722, "Longitude:", -76.60198)
Python

Output

My first box My second box Third box here Fourth box
Street: 231 S High St
City/Town: Baltimore
State: Maryland
ZipCode: 21202
Latitude: 39.286722 Longitude: -76.60198
Plaintext

Example #6: Escape characters

  • To escape certain characters use backslash().
  • Characters like single quote(‘), double quote(“), backslash() need to be escaped in certain cases. Just add a backslash before that special character and it will be escaped and printed as it is.
  • We don’t need to escape a single quote(‘) or double quote(“), if the whole string is not wrapped with the same quotation. For example, if the string is wrapped with single quote, and there is a double quote inside the string, then we don’t need to explicitly escape it.
print("The quick brown fox jumps over the lazy dog")
print('Time flies like an arrow')

print("Let's go to the park and enjoy the sunshine")
print('I won't be able to make it to the meeting tomorrow')

print("The sign read, "No entry after 10:00 PM"")
print('Name of the shop is "Books & Beyond"')

print("To escape a backslash (\) add a backslash before it")
print("Path of the Python execution file in windows is C:\python3\python.exe")
Python

Output

The quick brown fox jumps over the lazy dog
Time flies like an arrow
Let's go to the park and enjoy the sunshine
I won't be able to make it to the meeting tomorrow
The sign read, "No entry after 10:00 PM"
Name of the shop is "Books & Beyond"
To escape a backslash () add a backslash before it
Path of the Python execution file in windows is C:python3python.exe
Plaintext

Example #7: Special escape character

The following escape characters have special meanings. These characters do not normally show in the output but are mostly invisible.

These escape characters help us with formatting text. Here is a brief list of the escape characters, in the following table-

Escape CharacterCharacter Name
tTab
bBackspace
rCarriage return
nNew line

These escape characters can be used inside a string inside a print function, to format the output.

print("String part before tabtString part after tabtonettwotthreetfourtfive")
print("string part before backspacebstring part after backspace")
print('String part before carriage returnrString part after carriage return character')
print('string part before new linenstring part after new line')
Python

Output

String part before tab  String part after tab   one     two     three   four    five
string part before backspacstring part after backspace
String part after carriage return character
string part before new line
string part after new line
Plaintext

Example #8: Raw string

  • We can mark the string as raw, by adding a “r” character before the string(before the quotation mark).
  • If a string is marked as raw then all the characters(including the escape characters) are printed as is(with be backslashes).
print(r"This is an example of raw string printing.nThis includes new line and a backslash for path c:sometestpath")
Python

Output

This is an example of raw string printing.nThis includes new line and a backslash for path c:sometestpath
Plaintext

Example #9: String with Unicode characters

  • The print function is capable of printing Unicode characters without any special mechanism. Just put the character in the print() function parameter string, and it will be printed.
  • If we want to print a Unicode character using the code, then we have to add a “u” before the code of the character.
print("Example of a string that has a unicode character: Café")
print("Hello in Japanese is こんにちは")
print("Here is hello in Japanese using unicode u3053u3093u306bu3061u306f")
print("Here is an unicode character a: u0061")
print("Here is an unicode character for copyright: u00a9")
print("Here is an unicode of euro: u20ac")
Python

Output

Example of a string that has a unicode character: Café
Hello in Japanese is こんにちは
Here is hello in Japanese using unicode こんにちは
Here is an unicode character A: a
Here is an unicode character for copyright: ©
Here is an unicode of euro: €
Plaintext

Example #10: print with specific separator and end param

  • We can use the “sep” parameter and pass a separate value, to define a special separator between the provided string. The default value of “sep” param is a space character(” “). If we want to use a different separator in the output, then we can define using this parameter.
  • We can use the “end” param to define a special end character. The default value of “end” param is a new line(n).
print("first part of seperator example", "second part of seperator example", sep=" || BIGBOX SEPARATOR || ")
print("example of print in python with a separate ending", end="BIGBOXEND")
Python

Output

first part of seperator example || BIGBOX SEPARATOR || second part of seperator example
example of print in python with a separate endingBIGBOXEND
Plaintext

Example #11: Formatting in print

Formatting a string and adding values from variables is a common use of the print function. Here is how we can format a string while printing-

Case #1: Use the format function

  • To format a string for adding any value inside the string, we can define the place where the variable value will be added, by using “{}”.
  • Then we have to use the string “format” function and pass values to it.
  • The values passed to “format” should follow the same sequences as we want to place those in the string.
price = 99.99

print("Price of the item is: {}".format(price))
Python

Output:

Price of the item is: 99.99
Plaintext

Case #2: Use multiple params with format

  • We can pass as many parameters to the format functions, to fulfill our requirement.
street = "54 Shepherd"
city = "Oakville"
state = "Ontario"
zip = "L6K 2G5"
country = "Canada"
phoneNumber = "(905) 337-8111"

print("Address-nStreet: {}nCity: {}nState: {}nZip: {}nCountry: {}n".format(street, city, state, zip, country))
Python

Output:

Address-
Street: 54 Shepherd
City: Oakville
State: Ontario
Zip: L6K 2G5
Country: Canada
Plaintext

Case #3: Define position number with format

  • We can define the number of the marker by passing a numeric value inside “{}”, like “{1}”. This way the position of the parameters passed to the “format” function will be used to the defined marked places.
  • This is helpful when there are lots of params, and we want to keep the positions flexible. Also helpful when we want to use the same variable value multiple times in a string.
price = 75
itemCount = 5

print("Price of one item is {0}.nSo total amount is: {0} * {1} = {2}".format(price, itemCount, price * itemCount))
Python

Output:

Price of one item is 75.
So total amount is: 75 * 5 = 375
Plaintext

Case #4: Format a number while formatting

  • We can format a float number if we want by using the format after a color after the position number.

price = 75
itemCount = 5

# We can also format while printing values
print("Prices of one item is {0:.2f}.nSo total amount is: {0:.2f} * {1} = {2:.2f}".format(price, itemCount, price * itemCount))
Python

Output:

Prices of one item is 75.00.
So total amount is: 75.00 * 5 = 375.00
Plaintext

Case #5: Use named parameter in format

  • We can also use named parameters for the format function. 
  • Just define the identifier name inside the “{}” where we want to place it. And pass the values to the format function with the corresponding name.
name = " Johnny Hoppe"
gender = "male"

print("Name of the person is {name}, gender is {personGender} and date of birth {dob}".format(name=name, personGender=gender, dob="1993-09-21"))
Python

Output:

Name of the person is  Johnny Hoppe, gender is male and date of birth 1993-09-21
Plaintext

Case #3: Use “f” for formatting simply

  • We can add the “f” prefix to the string, to format the string.
  • Just pace the variable inside “{}”, and the value of the variable will be printed.
name = " Johnny Hoppe"
gender = "male"
dob = "1993-09-21"

print(f"Name of the person is {name}, gender is {gender} and date of birth {dob}")
Python

Output:

Name of the person is  Johnny Hoppe, gender is male and date of birth 1993-09-21
Plaintext

Definition in Source Code

In the Python source code, the definition of the function is as follows-

// Pythonbltinmodule.c

/*[clinic input]
print as builtin_print

    *args: object
    sep: object(c_default="Py_None") = ' '
        string inserted between values, default a space.
    end: object(c_default="Py_None") = 'n'
        string appended after the last value, default a newline.
    file: object = None
        a file-like object (stream); defaults to the current sys.stdout.
    flush: bool = False
        whether to forcibly flush the stream.

Prints the values to a stream, or to sys.stdout by default.

[clinic start generated code]*/

static PyObject *
builtin_print_impl(PyObject *module, PyObject *args, PyObject *sep,
                   PyObject *end, PyObject *file, int flush)
/*[clinic end generated code: output=3cfc0940f5bc237b input=c143c575d24fe665]*/
{
    int i, err;

    if (file == Py_None) {
        PyThreadState *tstate = _PyThreadState_GET();
        file = _PySys_GetAttr(tstate, &_Py_ID(stdout));
        if (file == NULL) {
            PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
            return NULL;
        }

        /* sys.stdout may be None when FILE* stdout isn't connected */
        if (file == Py_None) {
            Py_RETURN_NONE;
        }
    }

    if (sep == Py_None) {
        sep = NULL;
    }
    else if (sep && !PyUnicode_Check(sep)) {
        PyErr_Format(PyExc_TypeError,
                     "sep must be None or a string, not %.200s",
                     Py_TYPE(sep)->tp_name);
        return NULL;
    }
    if (end == Py_None) {
        end = NULL;
    }
    else if (end && !PyUnicode_Check(end)) {
        PyErr_Format(PyExc_TypeError,
                     "end must be None or a string, not %.200s",
                     Py_TYPE(end)->tp_name);
        return NULL;
    }

    for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
        if (i > 0) {
            if (sep == NULL) {
                err = PyFile_WriteString(" ", file);
            }
            else {
                err = PyFile_WriteObject(sep, file, Py_PRINT_RAW);
            }
            if (err) {
                return NULL;
            }
        }
        err = PyFile_WriteObject(PyTuple_GET_ITEM(args, i), file, Py_PRINT_RAW);
        if (err) {
            return NULL;
        }
    }

    if (end == NULL) {
        err = PyFile_WriteString("n", file);
    }
    else {
        err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
    }
    if (err) {
        return NULL;
    }

    if (flush) {
        if (_PyFile_Flush(file) < 0) {
            return NULL;
        }
    }

    Py_RETURN_NONE;
}
C++

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.