Formatting output from print on respective lines?
<p>I am trying to format the results of a query such that results are printed on their respective lines. For example, I am querying stores by store number and obtaining the location from a JSON file, but when printing, the store number and location are printing on separate lines:</p>

<p>Code Snippet: (Searching for stores 35 and 96)</p>

<pre><code>for store, data in results.items():
    print('Store: {}'.format(store))
    if data:
        for location in data:
            print(location)
</code></pre>

<p><strong>Current Output:</strong><br>
Store: 35<br>
{'location': Iowa}<br>
Store: 96<br>
{'location': Minnesota}</p>

<p><strong>Desired output (or something similar):</strong><br>
Store: 35, 'location': Iowa<br>
Store: 96, 'location': Minnesota</p>

<p>Adding <code>end=''</code> to your first print statement should fix the problem. By specifying that the end character is an empty string you will override the default <code>\n</code> character (by default print statements end with a new line character).</p>

<pre><code>for store, data in results.items():
    print('Store: {}'.format(store), end='')
    if data:
        for location in data:
            print(location)
</code></pre>

<p>We will only add <code>end=''</code> to the first print statement because we want the new line to print after you print out the location.</p>

<p>If you want to separate your prints with a <code>,</code> of course you would just add <code>+ ','</code> to your first print statement.</p>

<p>This will work right off the bat if you're using Python 3. If you're using Python 2.X you will have to add this line to the top of your file: <code>from __future__ import print_function</code></p>

<p>Here's a simple example of this in action:</p>

<pre><code>from __future__ import print_function

l1 = ['hello1', 'hello2', 'hello3']
l2 = ['world1', 'world2', 'world3']

for i,j in zip(l1, l2):
    print (i, end='')
    print (j)

Output:

hello1world1
hello2world2
hello3world3
</code></pre>

<p>If we took the same code but altered it slightly and just removed the <code>end=''</code>, this is what would happen:</p>

<pre><code>from __future__ import print_function

l1 = ['hello1', 'hello2', 'hello3']
l2 = ['world1', 'world2', 'world3']

for i,j in zip(l1, l2):
    print (i)
    print (j)

Output:

hello1
world1
hello2
world2
hello3
world3
</code></pre>

<p>As you can see each line would end with a new line character, this printing a new line for each statement.</p>

python python-3.x printing formatting