例如,如果我有
>>> 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"
最终选择权在您。
我是一名优秀的程序员,十分优秀!