I’m currently learning Python for data automation and I am confused about the formatting options within the print() function. I see both sep and end being used to modify output, but I can't quite grasp when to use one over the other. If I want to print a list of variables on a single line separated by commas, which one is responsible for that? And how do they interact when used together in a complex logging script? I want to make sure my console output is clean and easy for my team to read.
3 answers
The distinction lies in where the characters are placed. The sep (separator) parameter defines what string is placed between multiple objects passed into a single print call. By default, it is a space. For example, print("A", "B", sep="-") results in A-B. On the other hand, the end parameter defines what is printed at the very end of the print statement. By default, this is a newline character (\n), which is why every print call starts on a new line. If you change it to end=" ", the next print statement will continue on the same line. Understanding this is essential for creating progress bars or formatting CSV-style data directly in the console.
When you are building a loop to print values, do you find yourself using end more often than sep to prevent the console from scrolling too quickly?
Just remember: sep is for the "middle" of the items, and end is for the "finish line" of the statement. You can use them together like print(a, b, sep=', ', end='.').
I agree with Jennifer. It's a simple way to remember it. I used this exact combination recently to format a list of user IDs into a readable string for a report. It's much cleaner than using .join() for simple tasks.
That’s a common scenario, Michael. In data science, when we are printing training epochs or progress, we often use end="\r" (carriage return) so the output stays on one line and just updates the numbers. However, sep is much more useful when you have a tuple or a list of metrics that you want to display horizontally with specific spacing. They serve two different dimensions of formatting: sep handles the horizontal relationship between items in one call, while end handles the vertical relationship between consecutive calls