python输出结果换行,如何在f字符串中使用换行符'\n'格式化Python 3.6中的输出?

本文讨论了在Python f-string中插入换行符的问题,由于f-string内不能直接使用反斜杠,提出了三种解决方案:通过变量赋值、使用chr(10)以及预先拼接字符串的方法实现换行。同时,对比了f-string与str.format()在处理此类问题上的差异。
Python3.10

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

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)

The problem is that '\' cannot be used inside the {...} expression portions of an f-string.

Expected output:

Winners are:

Adam

Bob

Cyril

解决方案

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

This is specified in the PEP for f-strings:

Backslashes may not appear inside the expression portions of f-strings, [...]

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)

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)}"

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}"

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:

>>> "{\\} {*}".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 must for some reason use f-strings.

Just because something is new, doesn't mean you should try and do everything with it ;-)

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值