Cur*_*act 6 python indentation python-3.x f-string
我正在尝试在 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 some text
across multiple
lines.
}
Run Code Online (Sandbox Code Playgroud)
如何在不预先制表符内部字符串的情况下保留 fstring 的缩进?
这里的答案似乎都没有达到我想要的效果,所以我正在用一个尽可能接近我正在寻找的解决方案来回答我自己的问题。不需要预先对数据进行制表符来定义其缩进级别,也不需要不缩进行(这会破坏可读性)。相反, fstring 中当前行的缩进级别在使用时传递。
不完美但有效。
import textwrap
def code_indent(text, tab_sz, tab_chr=' '):
def indented_lines():
for i, line in enumerate(text.splitlines(True)):
yield (
tab_chr * tab_sz + line if line.strip() else line
) if i else line
return ''.join(indented_lines())
inner_str = textwrap.dedent(
'''\
This is some text
across multiple
lines.'''
)
full_str = textwrap.dedent(
f'''
data{{
{code_indent(inner_str, 8)}
}}'''
)
print(full_str)
Run Code Online (Sandbox Code Playgroud)