首页 > 解决方案 > 在python中使用字符串格式,生成重复的短信

问题描述

我有:

inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]
for item in inventory:
    print('The store has {1} {0}, each for {2} USD'.format(item))

我想得到:商店有 12 只鞋子,每只 29.99 美元。. .

标签: python

解决方案


您需要拆分itemin for 循环,以便可以在.format方法中使用这些值。

inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]
for item in inventory:
    print('The store has {1} {0}, each for {2} USD'.format(*item.split(',')))

推荐阅读