簡體   English   中英

如何使用 Python 3 中的 format 方法打印字符串列表中的項目

[英]How to Print items in a List of Strings using the format method in Python 3

提供有關商店庫存的數據列表,其中列表中的每個項目代表項目的名稱、庫存量和成本。 使用 .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.

我不清楚在使用格式方法時如何正確索引,因為我正在使用字符串列表。 我需要修復什么才能正確索引?

您有一個字符串列表,您需要將它們拆分為字段:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM