Reputation: 5
Python 3 - I am using a for loop to print values from a dictionary. Some dictionaries within rawData have "RecurringCharges" as an empty list. I am checking to see if the list is empty and either populating with "0.0" if empty or the "Amount" if populated.
Creating the IF statement in my For Loop presents a new print statement and prints to a new line. I would like it to be one continuous line.
for each in rawData['ReservedInstancesOfferings']:
print('PDX', ','
, each['InstanceType'], ','
, each['InstanceTenancy'], ','
, each['ProductDescription'], ','
, each['OfferingType'], ','
, each['Duration'], ','
, each['ReservedInstancesOfferingId'], ','
, each['FixedPrice'], ',',
)
if not each['RecurringCharges']:
print("0.0")
else:
print(each['RecurringCharges'][0].get('Amount'))
Upvotes: 0
Views: 1247
Reputation: 140148
Of course you could just follow How to print without newline or space?
but in that case, it would be better to insert your expression as the last argument in a ternary expression:
, each['ReservedInstancesOfferingId'], ','
, each['FixedPrice'], ','
, "0.0" if not each['RecurringCharges'] else each['RecurringCharges'][0].get('Amount')
)
Upvotes: 0
Reputation: 1267
Instead of using the print function, use stdout!
import sys
sys.stdout.write('this is on a line ')
sys.stdout.write('and this is on that same line!')
With sys.stdout.write(), if you want a newline, you put \n in the string, otherwise, it's on the same line.
Upvotes: 0
Reputation: 682
If using Python 3, add to the end of each print statement a comma and then end="", such as:
print(each['RecurringCharges'][0].get('Amount'), end="")
Upvotes: 2
Reputation: 5
I found the answer shortly after posting: include the parameter end='' in the first print statement.
for each in rawData['ReservedInstancesOfferings']:
print('PDX', ','
, each['InstanceType'], ','
, each['InstanceTenancy'], ','
, each['ProductDescription'], ','
, each['OfferingType'], ','
, each['Duration'], ','
, each['ReservedInstancesOfferingId'], ','
, each['FixedPrice'], ',', end=''
)
if not each['RecurringCharges']:
print("0.0")
else:
print(each['RecurringCharges'][0].get('Amount'))
Upvotes: 0