我正在尝试在python的format函数中使用\ n,因为不可能使用fstrings来实现。但我不确定如何完成。
raw_data = {'post 1': 'link 1', 'post 2': 'link 2'}
data = [("Post:{}\nLink: {}").format(title, link) for title, link in raw_data.items()]
print(data)
哪个打印:['Post:post 1\nLink: link 1\n', 'Post:post 2\nLink: link 2\n']
预期结果:
帖子:帖子1
链接:链接1
发布:发布2
链接:链接2
答案 0 :(得分:0)
您得到了:
>>> raw_data = {'post 1': 'link 1', 'post 2': 'link 2'}
>>> data = [("Post:{}\nLink: {}").format(title, link) for title, link in raw_data.items()]
>>> print(data)
['Post:post 1\nLink: link 1', 'Post:post 2\nLink: link 2']
这不是您期望的,但这是Python正常的输出。参见the doc:
所有非关键字参数都像str()一样转换为字符串,并写入流中
让我们尝试一下:
>>> str(data)
"['Post:post 1\\nLink: link 1', 'Post:post 2\\nLink: link 2']"
请注意结果的双引号和双反斜杠:str(data)
是代表列表的字符串,print
打印该字符串,而不是其内容。与以下内容完全不同:
>>> for s in data: print(s)
...
Post:post 1
Link: link 1
Post:post 2
Link: link 2
要关注差异,请看一个字符串:
>>> s = "a\nb"
>>> s # the value of the string s
'a\nb'
>>> print(s) # outputs the string s
a
b
总结:打印列表元素与打印列表本身不同。使用for s in data: print(s)
来获取想要的东西。
编辑,如果要从函数返回可打印的结果,则必须构建自己的字符串,即data[0]+"\n"+data[1]
或使用join
:>
>>> s = "\n".join(data)
>>> s # return this string
'Post:post 1\nLink: link 1\nPost:post 2\nLink: link 2'
>>> print(s)
Post:post 1
Link: link 1
Post:post 2
Link: link 2
答案 1 :(得分:0)
为了使用return
格式化列表,我不得不将所述列表转换为字符串。
所以我做到了:
raw_data = {'post 1': 'link 1', 'post 2': 'link 2'}
data = [("Post:{}\nLink: {}").format(title, link) for title, link in raw_data.items()]
return ''.join(data)