【发布时间】:2019-07-24 03:35:51
【问题描述】:
我正在尝试在 Python3(.7) 中使用三引号字符串来构建一些格式化字符串。
我有一个内部字符串列表,都需要在其中添加标签:
This is some text
across multiple
lines.
还有一个应该包含内部字符串的字符串
data{
// string goes here
}
创建内部字符串时,我无法对其进行制表符。所以,我的想法是使用dedent 和 Python3 三重引号 fstrings:
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)
但是,缩进没有被维护:
data{
// This should all be tabbed
This is some text
across multiple
lines.
}
想要的结果:
data{
// This should all be tabbed
This is some text
across multiple
lines.
}
如何在不预先标记内部字符串的情况下保留 fstring 的缩进?
【问题讨论】:
-
您是否尝试过使用
\n和\t作为格式化选项?
标签: python python-3.x indentation f-string