gpt4 book ai didi

python - 有没有办法在大括号内分解 f 弦?

转载 作者:太空宇宙 更新时间:2023-11-04 09:54:18 28 4
gpt4 key购买 nike

例如,如果我有

>>> name = f"{os.path.splitext(os.path.basename('/some/long/path/I/donot/need/to/some/config.bs'))[0]}.yaml"
'config.yaml'

因为实际文本很少,所以在 79 个字符之前没有好的地方可以换行。看来你不能这样做:

name = f"{os.path.splitext(os.path.basename(
'/some/long/path/I/donot/need/to/some/config.bs'))[0]}.yaml"

>>> f"{os.path.splitext(os.path.basename(
File "<stdin>", line 1
f"{os.path.splitext(os.path.basename(
^
SyntaxError: EOL while scanning string literal

我唯一能做的就是拆分命令,例如:

>>> fname = '/some/long/path/I/donot/need/to/some/config.bs'
>>> tempname = os.path.splitext(os.path.basename(
... fname))[0]
>>> name = f'{tempname}.yaml'
>>> name
'config.yaml'

是否有任何其他选项来拆分 f 字符串?

最佳答案

是的,您仍然可以使用三引号字符串并以您认为最好的任何方式拆分它。

From the PEP on f-strings :

Leading and trailing whitespace in expressions is ignored

For ease of readability, leading and trailing whitespace in expressions is ignored. This is a by-product of enclosing the expression in parentheses before evaluation.

所以删除前后的任何空格,括号内的额外空格(例如函数调用)和方/大括号也没有区别,原因相同。所以这个:

name = f"""{
os.path.splitext(
os.path.basename('/some/long/path/I/donot/need/to/some/config.bs')
)[0]}.yaml"""

仍应产生预期的结果。以您认为最好的方式对其进行格式化。

尽管有人可以成功地争辩说您可以通过其他几个步骤减少所有内容:

# not using fully qualified name
from os.path import splitext, basename

fname = '/some/long/path/I/donot/need/to/some/config.bs'
name = f"{splitext(basename(fname))[0].yaml"

最终选择权在您。

关于python - 有没有办法在大括号内分解 f 弦?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46495720/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com