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>I would write all the output in a variable and print the variable only once at the end. This also allows you to save time (despite using more memory) since you need only a single access to the stdout. The code is also easier to follow (in my opinion):</p>

<pre><code>output = ''
for store, data in results.items():
    output += 'Store: {}'.format(store)
    if data:
        for location in data:
            output += location+'\n'

# Only at the end you print your output
print(output)
</code></pre>

<p>You can also print at the end of each iteration (you still access half of the times to the stdout) with the following:</p>

<pre><code>for store, data in results.items():
    output = 'Store: {}'.format(store)
    if data:
        for location in data:
            output += location+'\n'

    # Print only at the end of the loop
    print(output)
</code></pre>

<p>If you want a new line for each Store but not for each "location":</p>

<pre><code>output = ''
for store, data in results.items():
    output += 'Store: {}'.format(store)
    if data:
        for location in data:
            output += location
        output += '\n'

# Only at the end you print your output
print(output)
</code></pre>

<p>I think this approach is much more flexible, easier to read in the code and is also faster.</p>

<p>Hope to be helpful</p>

python python-3.x printing formatting