Python end parameter in print()
In Python, the print() function, commonly used for displaying output, by default ends each statement with a newline character (\n), but this behavior can be customized using the end parameter, which allows you to specify a different string (such as a space, comma, or hyphen) to be printed at the end, enabling multiple outputs to appear on the same line or with custom separators. Example:
print("Welcome to", end = ' ')
print("GeeksforGeeks", end= ' ')
Output
Welcome to GeeksforGeeks
Syntax of find() method
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
- end='\n' is the default setting, meaning each print ends with a newline.
- You can change the end value to anything you like a space, tab, special character or even an empty string.
Examples
Example 1: This example shows how Python's end parameter in print() controls output formatting. By default, print() adds a newline but end lets you customize what appears after the output like a space, tab or nothing.
print("Hello")
print("World")
print("Hello", end=" ")
print("World")
Output
Hello World Hello World
Explanation: In this example, the first two print() statements print "Hello" and "World" on separate lines by default. In the second case, end=" " replaces the newline with a space, so "World" appears on the same line as "Hello".
Example 2: In this example, we use the end parameter to print numbers from a loop on the same line, separated by commas instead of newlines.
for i in range(5):
print(i, end=", ")
Output
0, 1, 2, 3, 4,
Explanation: In this example, the end=", " parameter is used in the print() statement to print each number in the range on the same line, separated by a comma and a space. Without this, each number would be printed on a new line by default.