如何在 f-string 中使用换行符 '\n' 来格式化 Python 3.6 中的输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44780357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use newline '\n' in f-string to format output in Python 3.6?
提问by malmed
I would like to know how to format this case in a Pythonic way with f-strings:
我想知道如何使用 f-strings 以 Pythonic 的方式格式化这个案例:
names = ['Adam', 'Bob', 'Cyril']
text = f"Winners are:\n{'\n'.join(names)}"
print(text)
The problem is that '\'
cannot be used inside the {...}
expression portions of an f-string.
Expected output:
问题是'\'
不能在{...}
f 字符串的表达式部分内使用。预期输出:
Winners are:
Adam
Bob
Cyril
回答by Dimitris Fasarakis Hilliard
You can't. Backslashes cannot appear inside the curly braces {}
; doing so results in a SyntaxError
:
你不能。反斜杠不能出现在花括号内{}
;这样做会导致SyntaxError
:
>>> f'{\}'
SyntaxError: f-string expression part cannot include a backslash
This is specified in the PEPfor f-strings:
这是在PEP 中为 f 字符串指定的:
Backslashes may not appear inside the expression portions of f-strings, [...]
反斜杠可能不会出现在 f 字符串的表达式部分中,[...]
One option is assinging '\n'
to a name and then .join
on that inside the f
-string; that is, without using a literal:
一种选择是分配'\n'
一个名称,然后.join
在f
-string 中分配名称;也就是说,不使用文字:
names = ['Adam', 'Bob', 'Cyril']
nl = '\n'
text = f"Winners are:{nl}{nl.join(names)}"
print(text)
Results in:
结果是:
Winners are:
Adam
Bob
Cyril
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)}"
另一种选择,如@wim规定,就是用chr(10)
得到\n
恢复,然后加入那里。f"Winners are:\n{chr(10).join(names)}"
Yet another, of course, is to '\n'.join
beforehand and then add the name accordingly:
当然,还有一个是'\n'.join
预先添加名称,然后相应地添加名称:
n = "\n".join(names)
text = f"Winners are:\n{n}"
which results in the same output.
这导致相同的输出。
Note:
笔记:
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:
这是f
-strings 和str.format
. 在后者中,您始终可以使用标点符号,只要解压缩包含这些键的相应古怪字典:
>>> "{\} {*}".format(**{"\": 'Hello', "*": 'World!'})
"Hello World!"
(Please don't do this.)
(请不要这样做。)
In the former, punctuation isn't allowed because you can't have identifiers that use them.
在前者中,不允许使用标点符号,因为您不能拥有使用它们的标识符。
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 mustfor some reason use f-strings.
旁白:我肯定会选择print
or format
,正如其他答案所建议的那样。我给出的选项仅适用于出于某种原因必须使用 f 字符串的情况。
Just because something is new, doesn't mean you should try and do everything with it ;-)
仅仅因为某些东西是新的,并不意味着你应该尝试用它做所有事情;-)
回答by Eugene Yarmash
You don't need f-strings or other formatters to print a list of strings with a separator. Just use the sep
keyword argument to print()
:
您不需要 f 字符串或其他格式化程序来打印带有分隔符的字符串列表。只需使用sep
关键字参数print()
:
names = ['Adam', 'Bob', 'Cyril']
print('Winners are:', *names, sep='\n')
Output:
输出:
Winners are:
Adam
Bob
Cyril
That said, using str.join()
/str.format()
here would arguably be simpler and more readable than any f-string workaround:
也就是说,在这里使用str.join()
/str.format()
可以说比任何 f-string 解决方法更简单、更具可读性:
print('\n'.join(['Winners are:', *names]))
print('Winners are:\n{}'.format('\n'.join(names)))
回答by Chris_Rands
You can't use backslashes in f-strings as others have said, but you could step around this using os.linesep
(although note this won't be \n
on all platforms, and is not recommended unless reading/writing binary files; see Rick'scomments):
您不能像其他人所说的那样在 f 字符串中使用反斜杠,但您可以使用os.linesep
(尽管请注意这不会\n
在所有平台上使用,除非读取/写入二进制文件,否则不推荐使用;请参阅Rick 的评论):
>>> import os
>>> names = ['Adam', 'Bob', 'Cyril']
>>> print(f"Winners are:\n{os.linesep.join(names)}")
Winners are:
Adam
Bob
Cyril
Or perhaps in a less readable way, but guaranteed to be \n
, with chr()
:
或者也许以一种不太可读的方式,但保证是\n
,与chr()
:
>>> print(f"Winners are:\n{chr(10).join(names)}")
Winners are:
Adam
Bob
Cyril
回答by Rick supports Monica
The other answers give ideas for how to put the newline character into a f-string field. However, I would argue that for the example the OP gave (which may or may not be indicative of OP's actual use case), none of these ideas should actually be used.
其他答案给出了如何将换行符放入 f 字符串字段的想法。但是,我认为对于 OP 给出的示例(这可能表示也可能不表示 OP 的实际用例),实际上不应使用这些想法中的任何一个。
The entire point of using f-strings is increasing code readability. There is nothing you can do with f-strings that you cannot do with format
. Consider carefully whether there is anything more readableabout this (if you could do it):
使用 f-strings 的全部意义在于提高代码的可读性。使用 f-strings 没有什么是你无法使用的format
。仔细考虑是否有任何关于此的更具可读性的内容(如果你能做到的话):
f"Winners are:\n{'\n'.join(names)}"
...or this:
...或这个:
newline = '\n'
f"Winners are:\n{newline.join(names)}"
...or this:
...或这个:
"Winners are:\n{chr(10).join(names)}"
vs. this:
与这个:
"Winners are:\n{}".format('\n'.join(names))
The last way is at least as readable, if not more so.
最后一种方法至少是可读的,如果不是更多的话。
In short: don't use a hammer when you need a screwdriver just because you have a shiny new one. Code is read much more often than it is written.
简而言之:当你需要一把螺丝刀时,不要仅仅因为你有一把闪亮的新螺丝刀就使用锤子。代码的阅读次数远多于编写次数。
For other use cases, yes, it's possible the chr(10)
idea or newline
idea may be appropriate. But not for the one given.
对于其他用例,是的,这个chr(10)
想法或newline
想法可能是合适的。但不是给定的。