python - 如何将列表插入 Python 中的 f 字符串?

标签 python string python-3.6 f-string

假设我有一个函数

def foo(): return [1, 2, 3]

我想将函数的结果插入到字符串中以获得 "001 002 003"。我试过这个:

f"{*foo():03d 03d 03d}"

但它产生了SyntaxError: Can't use starred expression here。我可以使用 f 弦来做到这一点吗?

最佳答案

这是你要找的吗?

str_repr = ' '.join(map('{:03d}'.format, foo()))
print(str_repr)  # prints: 001 002 003

也许此解决方案的最佳之处在于它适用于任何列表长度,并且只需进行最少的调整,您也可以更改输出格式。

关于python - 如何将列表插入 Python 中的 f 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41896356/

相关文章:

python - 在字典中附加列表的最佳方法是什么?

Windows Server 2012 R2 x64 上带有 Python 3.6.4 的 OpenCV 导入 cv2 : DLL not found

python - 使用 f-string 的查询格式

string - 从 Common Lisp 中的字符串中选择随机字符

python - 在 Python 3.6 中运行 Flask 开发服务器会引发 SocketServer 和 ForkingMixIn 的 ImportError

python - 如何查看read_csv的进度条

Python SyntaxError : invalid syntax, python3 中的函数参数是否允许使用括号?

Python安装工具: quick way to add scripts without "main" function as "console_scripts" entry points

javascript - 比较不同编码的字符串

r - 统计这个因子中 "0"的个数