如何在包含多行字符串变量的多行f-string中正确处理缩进?
如何在包含多行字符串变量的多行f-string中正确处理缩进?
我知道我们可以使用textwrap.dedent()来处理多行字符串的缩进问题,但如果是包含多行字符串变量替换的多行f-string,情况就有点复杂了。
下面的例子中,多行字符串被故意缩进,用来模拟它们嵌套在其他结构中的场景:
from textwrap import dedent block_a = """\ Line one Line two""" block_b = """\ Line four Line five""" blocks = f"""\ {block_a} Line three {block_b}""" print(dedent(blocks))
我想要的输出结果是:
Line one Line two Line three Line four Line five
但只对blocks做dedent显然不够,得到的结果是:
Line one Line two Line three Line four Line five
而同时对block_a和block_b做dedent也没太大帮助:
blocks = f"""\ {dedent(block_a)} Line three {dedent(block_b)}""" print(dedent(blocks))
得到的结果变成了:
Line one Line two Line three Line four Line five
我真正想要的是,那些被替换的字符串应该和我放置替换字段的位置保持相同的缩进级别,同时保留变量内部的缩进。之后我可以通过整体dedent得到预期结果。
在整体dedent之前,上面的例子中我想要的中间状态是:
Line one Line two Line three Line four Line five
如果替换字段和Line three都多缩进4个空格,比如:
blocks = f"""\ {dedent(block_a)} Line three {dedent(block_b)}"""
我期望的中间状态是:
Line one Line two Line three Line four Line five
我目前有一个变通方案,不用f-string而是用格式化字符串:
blocks = """\ {} Line three {}""" print(dedent(blocks).format(dedent(block_a), dedent(block_b)))
但我还是想知道有没有办法用f-string实现这个需求,以及其他能处理这类缩进问题的方法。
备注:内容来源于stack exchange,提问作者adamkwm
相关产品推荐
相关产品推荐

