简体   繁体   中英

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

Provided is a list of data about a store's inventory where each item in the list represents the name of an item, how much is in stock, and how much it costs. Print out each item in the list with the same formatting, using the .format method (not string concatenation). For example, the first print statement should read The store has 12 shoes, each for 29.99 USD.

I initialized an index variable, i, to 0 and wrote for loop with a loop variable to go through the contents in the list.

I then have a print statement, that will print "The store has {} {}, each for {} USD." that utilizes the format method to fill in the appropriate values for the bracket. For the format method, I have used i for my index variable to index through the list. I then increment my index variable by 1 for the next loop run until the loop iterates through the list.

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 expected result should be - The store has 12 shoes, each for 29.99 USD.

However, the way my code is written, I'm getting - The store has shoes, 12, 29.99 shoes, 12, 29.99, each for shoes, 12, 29.99 USD.

I'm unclear of how to index correctly when using the format method since I'm working with a list of strings. What do I need to fix to index correctly?

You have a list of strings there, you need to split them into fields:

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

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