通过遍历列表构造f字符串 [英] Constructing an f-string by for-looping through a list

查看:49
本文介绍了通过遍历列表构造f字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何去做:

mylist = [10, 20, 30]

对此:

'Quantity 10, quantity 20 quantity 30'

我知道可以这样:

mystring = f"Quantity {mylist[0]}, quantity {mylist[1]} quantity {mylist[2]}"

但是在构造f字符串时,是否没有一种方法可以包含一个for循环,而不是必须一个个地提供所有列表索引?

but isn't there a way to incorporate a for-loop when constructing the f-string instead of having to provide all the list indexes one by one?

Quantity quantity quantity 恰好是同一字符串,但它们可能类似于'数量 10, rank 20 王国和社会 30'.因此,数字之间会有不同的文字.

Quantity, quantity, and quantity just happen to be the same string, but they could be anything like 'Quantity 10, rank 20 kingdom and sovrenity 30'. So, there would be different text between the numbers.

推荐答案

您可以使用列表理解

", ".join([f"Quantity {x}" for x in mylist])

如果您关心大写字母......

And if you care about the capitalisation....

f"Quantity {mylist[0]}, " + ", ".join([f"quantity {x}" for x in mylist[1:]])

如果单词将有所不同,则需要将其压缩以进行理解

If the words are going to be different you need to zip them for the comprehension

words=["word1", "word2", "word3"]
numbers=[10,20,30]

', '.join([str(word) + " " + str(number) for word,number in zip(words,numbers)]).capitalize()

这篇关于通过遍历列表构造f字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆