简体   繁体   中英

How to print to the same line - If Statement within a For Loop

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'))

如果使用Python 3,请在每个打印语句的末尾添加一个逗号,然后添加end =“”,例如:

 print(each['RecurringCharges'][0].get('Amount'), end="")

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'))

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.

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')
      )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM