【问题标题】:How to Print items in a List of Strings using the format method in Python 3如何使用 Python 3 中的 format 方法打印字符串列表中的项目
【发布时间】:2019-09-09 05:04:23
【问题描述】:

提供的是有关商店库存的数据列表,其中列表中的每个项目代表项目的名称、库存量和成本。使用 .format 方法(不是字符串连接)以相同的格式打印出列表中的每个项目。例如,第一个打印语句应为商店有 12 只鞋子,每只 29.99 美元。

我将索引变量 i 初始化为 0,并用循环变量编写了 for 循环以遍历列表中的内容。

然后我有一个打印语句,它将打印“商店有 {} {},每个 {} USD。”它利用 format 方法为括号填写适当的值。对于格式方法,我使用 i 作为索引变量来索引列表。然后,为了下一次循环运行,我将索引变量增加 1,直到循环遍历列表。

inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]

i = 0

for item in inventory:
    print("The store has {} {}, each for {} USD.".format(inventory[i], inventory[i], inventory[i]))
    i += 1

预期的结果应该是 - The store has 12 shoes, each for 29.99 USD.

但是,我的代码编写方式是 - The store has shoes, 12, 29.99 shoes, 12, 29.99, each for shoes, 12, 29.99 USD.

我不清楚在使用格式方法时如何正确索引,因为我正在处理字符串列表。我需要修复什么才能正确索引?

【问题讨论】:

    标签: python string list indexing format


    【解决方案1】:

    你有一个字符串列表,你需要将它们分成字段:

    for item in inventory:
        item_desc, number, cost = item.split(", ")
        print(f"The store has {item_desc} {number}, each for {cost} USD.")
    
    

    【讨论】:

    • 您无需担心索引 - 循环已经一次为您提供一项。
    • 使用 split() 并分配给不同的变量非常有意义且有效!我不会想到这一点,感谢您提供如此干净的解决方案!
    【解决方案2】:
    inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]
    for i in inventory:
        ``str1 = []
        str1 = i.split(", ")
        print("The store has {} {}, each for {} USD.".format(str1[1],str1[0],str1[2]))
    

    【讨论】:

    • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的答案添加解释并说明适用的限制和假设。
    【解决方案3】:
    inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]
    for item in inventory:
        item = item.split(",")
        print("The store has{qua} {pro}, each for{price} USD.".format(pro = item[0],qua = item[1] ,price = item[2]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      相关资源
      最近更新 更多