如何在f字符串中使用换行符'\ n'格式化Python 3.6中的输出? [英] How to use newline '\n' in f-string to format output in Python 3.6?
问题描述
我想知道如何使用f字符串以Python的方式格式化这种情况:
I would like to know how to format this case in a Pythonic way with f-strings:
names = ['Adam', 'Bob', 'Cyril']
text = f"Winners are:\n{'\n'.join(names)}"
print(text)
问题是'\'
不能在f字符串的{...}
表达式部分内使用.
预期输出:
The problem is that '\'
cannot be used inside the {...}
expression portions of an f-string.
Expected output:
Winners are:
Adam
Bob
Cyril
推荐答案
您不能.反斜杠不能出现在花括号{}
内;这样做会导致SyntaxError
:
You can't. Backslashes cannot appear inside the curly braces {}
; doing so results in a SyntaxError
:
>>> f'{\}'
SyntaxError: f-string expression part cannot include a backslash
在 PEP 中为f-字符串:
反斜杠可能不会出现在f字符串的表达式部分[...]
Backslashes may not appear inside the expression portions of f-strings, [...]
一个选项是将'\n'
命名为一个名称,然后在f
-string内的名称上添加.join
;也就是说,不使用文字:
One option is assinging '\n'
to a name and then .join
on that inside the f
-string; that is, without using a literal:
names = ['Adam', 'Bob', 'Cyril']
nl = '\n'
text = f"Winners are:{nl}{nl.join(names)}"
print(text)
结果:
Winners are:
Adam
Bob
Cyril
由@wim指定的另一个选项是使用chr(10)
来获取返回的\n
,然后在该处加入. f"Winners are:\n{chr(10).join(names)}"
Another option, as specified by @wim, is to use chr(10)
to get \n
returned and then join there. f"Winners are:\n{chr(10).join(names)}"
当然,另一个方法是事先到达'\n'.join
,然后相应地添加名称:
Yet another, of course, is to '\n'.join
beforehand and then add the name accordingly:
n = "\n".join(names)
text = f"Winners are:\n{n}"
这将导致相同的输出.
这是f
-strings和str.format
之间的细微差别之一.在后者中,只要解压缩了包含这些键的相应古怪字典,您就可以始终使用标点符号:
This is one of the small differences between f
-strings and str.format
. In the latter, you can always use punctuation granted that a corresponding wacky dict is unpacked that contains those keys:
>>> "{\\} {*}".format(**{"\\": 'Hello', "*": 'World!'})
"Hello World!"
(请不要这样做.)
在前一种情况下,标点符号是不允许的,因为您没有使用它们的标识符.
In the former, punctuation isn't allowed because you can't have identifiers that use them.
此外:我肯定会选择print
或format
,因为其他答案也可以作为替代选择.我给出的选项仅在必须出于某种原因使用f字符串的情况下适用.
Aside: I would definitely opt for print
or format
, as the other answers suggest as an alternative. The options I've given only apply if you must for some reason use f-strings.
仅仅是因为有些新事物,并不意味着您应该尝试使用它做一切;-)
Just because something is new, doesn't mean you should try and do everything with it ;-)
这篇关于如何在f字符串中使用换行符'\ n'格式化Python 3.6中的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!