小编Cur*_*act的帖子

在三引号 fstring 中保留缩进

我正在尝试在 Python3(.7) 中使用三引号字符串来构建一些格式化字符串。

我有一个内部字符串列表,所有这些都需要添加到:

    This is some text
    across multiple
    lines.
Run Code Online (Sandbox Code Playgroud)

以及一个应包含内部字符串的字符串

data{
    // string goes here
}
Run Code Online (Sandbox Code Playgroud)

创建内部字符串时我无法制表符。dedent所以,我的想法是与 Python3 三引号 fstring 一起使用:

import textwrap

inner_str = textwrap.dedent(
    '''\
    This is some text
    across multiple
    lines.'''
)

full_str = textwrap.dedent(
    f'''\
    data{{
        // This should all be tabbed
        {inner_str}
    }}'''
)

print(full_str)
Run Code Online (Sandbox Code Playgroud)

但是,不会保留缩进:

    data{
        // This should all be tabbed
        This is some text
across multiple
lines.
    }
Run Code Online (Sandbox Code Playgroud)

期望的结果:

data{
    // This should all be tabbed
    This is …
Run Code Online (Sandbox Code Playgroud)

python indentation python-3.x f-string

6
推荐指数
1
解决办法
2615
查看次数

标签 统计

f-string ×1

indentation ×1

python ×1

python-3.x ×1