Skip to content

end keyword in Python

  • by

In Python, the end keyword is often used in the print() function to specify what character(s) should be printed at the end of each printed statement. By default, the print() function adds a newline character ('\n') at the end of the printed output. However, you can change this behavior using the end parameter.

Here’s the syntax for using the end keyword in the print() function:

print("Hello, ", end="")
print("world!")

By setting end="", you’re instructing the print() function not to add a newline character after the first print statement, so the second print statement continues on the same line.

end keyword in Python example

Let’s consider a scenario where you want to print a series of numbers on the same line, separated by a custom delimiter.

Suppose you have a list of numbers and you want to print them all on the same line, separated by commas and a space. You can use the end parameter to achieve this:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num, end=", ")

Output:

end keyword in Python

In this example, the end parameter is used to specify that a comma and a space should be added at the end of each print() call, rather than the default newline character. As a result, all the numbers are printed on the same line, separated by the desired delimiter.

Note:The last comma and space are included at the end of the output because the end parameter is applied after each print() call, including the last one. If you want to avoid the trailing comma and space, you can adjust the logic accordingly.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *