in fact this should not be a problem because it\'s fairly basic. I just want to print out an array of categories, but in one line and separated by comma.
for ent
Printing to the terminal in Python 3 is usually "line buffered". That is, the whole line is only printed to the terminal once a newline character is encountered.
To resolve this problem you should either print a new line at the end of the for loop, or flush stdout.
eg.
for entry in categories:
print(entry, ", ", end='')
print(end='', flush=True) # or just print() if you're not fussed about a newline
However, there are better ways of printing an array out. eg.
print(", ".join(str(entry) for entry in categories))
# or
print(*categories, sep=", ")
You are almost certainly experiencing output buffering by line. The output buffer is flushed every time you complete a line, but by suppressing the newline you never fill the buffer far enough to force a flush.
You can force a flush using flush=True
(Python 3.3 and up) or by calling the flush()
method on sys.stdout
:
for entry in categories:
print(entry, ", ", end='', flush=True)
You could simplify that a little, make ,
the end
value:
for entry in categories:
print(entry, end=', ', flush=True)
to eliminate the space between the entry and the comma.
Alternatively, print the categories as one string by using the comma as the sep
separator argument:
print(*categories, sep=', ')
Check categories
isn't empty - that'd make it print nothing - also I'd consider changing your code to make use of the sep
argument instead (depending how large categories
is):
print(*categories, sep=', ')
eg:
>>> categories = range(10)
>>> print(*categories, sep=', ')
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Then you don't have to worry about flushing/trailing separators etc...