1 min read

How to print() without a newline in Python 3

How to print() without a newline in Python 3

I'm building a command line tool that takes a while to run. I wanted a bit of a progress bar and tried to print('.') on each iteration, but ended up with an endless scroll.

In Python 3, you can use the "end" parameter in the print function to specify what character(s) should be printed at the end of the line. By default, this is a newline character ("\n"), but you can set it to an empty string ("") to prevent the newline from being printed:

chars = ['h', 'a', 'i', 'h', 'a', 'i']
for c in chars: 
	print(c, end=' ', flush=True)
    
# h a i h a i

This is what my progress bar looked like:

for phrase in phrases:
	if phrase.lower() in story.get('title').lower() \
    	or phrase.lower() in story.get('url', '').lower():
			save_story(story)
            print_story(story)
    else: 
    	print(story.get('title')[0], end="", flush=True)

When I didn't use the flush=True, I wouldn't get output until the next ~normal print() statement. Not sure why.