如何漂亮地打印 f 字符串?

问题描述

尝试从 f-string 打印字典:

import pprint as pp

my_dict = {
    "key_a": ["here","are","the","things"],"key_b": ["that","i","want"],"key_b": ["to","share","with","worlddddddddddddddddddddd"]
}

pp.pprint(f"Let's talk about all of these things:\n\n{my_dict}")

输出(不漂亮):

("Let's talk about all of these things:\n"
 '\n'
 "{'key_a': ['here','are','the','things'],'key_b': ['to','share','with',"
 "'the','worlddddddddddddddddddddd']}")

有没有办法在 f-strings 中完成这项工作,所以我不必pp.pprint(my_dict)

解决方法

不是真的。您可以做的最接近的是使用 pformat,即没有 pprintprint

print(f"Let's talk about all of these things:\n\n{pp.pformat(my_dict)}")