pla*_*etp 11 python string python-3.6 f-string
说我有一个功能
def foo(): return [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
我想将函数的结果插入到字符串中以获取"001 002 003".我试过这个:
f"{*foo():03d 03d 03d}"
Run Code Online (Sandbox Code Playgroud)
但它产生了SyntaxError: can't use starred expression here.我可以用f-string做这个吗?
这是你想要的?
str_repr = ' '.join(map('{:03d}'.format, foo()))
print(str_repr) # prints: 001 002 003
Run Code Online (Sandbox Code Playgroud)
也许关于这个解决方案的最好的事情是它适用于任何列表长度,并且通过最小的调整,您也可以更改输出格式.
带星号的表达式只允许在少数特定上下文中使用,例如函数调用、列表/元组/集合文字等。 f-string 占位符显然不是其中之一。您可以单独格式化每个元素并加入字符串,例如:
lst = foo()
s = ' '.join(f'{x:03d}' for x in lst) # '001 002 003'
Run Code Online (Sandbox Code Playgroud)
通常,要格式化多个值,您必须为每个值使用单独的占位符。