如何使用.format将列表元素插入字符串并输出多个字符串?



我正在尝试将列表中的元素插入到字符串中,并输出所有结果字符串。

这是我的清单:

fruit = ['Apple', 'Orange', 'Mango', 'Banana']

这是我的字符串:

my_string = The store is selling {}

我希望我的结果字符串看起来像这样:

The store is selling Apple
The store is selling Orange
The store is selling Mango
The store is selling Banana

到目前为止我写的是:

i = 0
while i < len(fruit):
i = i + 1
new_strings = my_string.format(fruit[i - 1])
print(new_strings)

当print(new_strings)在循环内时,这确实打印我想要的(所有结果4个字符串),但是当我尝试在while循环外打印(new_strings)时,它只打印最后一个字符串:

The store is selling Banana

如何让print(new_strings)在while循环外打印?是我的代码有问题吗?非常感谢任何帮助。谢谢你。

可以使用f字符串。它们易于使用并且是最佳实践!

fruits = ["Apple", "Orange", "Mango", "Banana"]
for fruit in fruits:
print(f"The store is selling {fruit}")

使用f字符串或格式化字符串字面值和列表推导式:

fruit = ['Apple', 'Orange', 'Mango', 'Banana']
strs = [f'The store is selling {x}' for x in fruit]
print(strs)
# or
for s in strs:
print(s)

更接近你原来的方法,试试下面的代码:

fruit = ['Apple', 'Orange', 'Mango', 'Banana']
list_of_strings = []
for fruit in fruits:
list_of_strings.append(f"The store is selling {fruit}")

print(list_of_strings)

相关内容

  • 没有找到相关文章

最新更新