问题
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?
回答1:
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.")
回答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]))
来源:https://stackoverflow.com/questions/55753148/how-to-print-items-in-a-list-of-strings-using-the-format-method-in-python-3