如何在For循环中打印到同一行If语句

2024-05-13 03:02:55 发布

您现在位置:Python中文网/ 问答频道 /正文

Python3- 我正在使用for循环从字典中打印值。rawData中的一些字典将“RecurringCharges”作为空列表。我正在检查列表是否为空,如果为空,则填充“0.0”或填充“数量”。在

在For循环中创建IF语句将显示一个新的print语句并打印到新行。我希望它是一条连续的线。在

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

Tags: in列表for数量if字典语句python3
3条回答

不要使用print函数,而是使用stdout!在

import sys
sys.stdout.write('this is on a line ')
sys.stdout.write('and this is on that same line!')

与系统标准输出写入(),如果要换行,请将\n放入字符串中,否则,它在同一行。在

我在发布后不久找到了答案:在第一个print语句中包含参数end=''。在

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

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

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

相关问题 更多 >