目前,如果我想格式化字符串并显示可变数量的{} s,我可能会写一些类似的内容:
data = [1, 2, 3]
print(("It's as easy as {}" + ((len(data)-1)*", {}")).format(*data))
我想弄清楚如何用f-string做到这一点,但是:
print(f"It's as easy as {data[0]}" + ((len(data)-1)*", {*data}"))
给了我:
It's as easy as 1, {*data}, {*data}, {*data}
我对Python很新。关于如何进行的任何提示?
答案 0 :(得分:0)
我认为使用str.join()
的某些策略可能是您最好的选择。像
f"It's as easy as {', '.join(map(str, data))}"
但是,这有点笨拙。我可能会为更干净的代码编写一个单独的函数
def commas(l):
return ', '.join(map(str, data))
print(f"It's as easy as {commas(data)}")
# It's as easy as 1, 2, 3