Python 块格式化
如何在字符串格式化上下文中缩进多行字符串?例如
'''
<
%s
>
''' % (paragraph)
,段落包含换行符。 ('foo\nbar')
如果我使用上面的代码,我会得到这样的输出:
'''
<
foo
bar
>
'''
当我真的想要这个时:
'''
<
foo
bar
>
'''
我知道我可以做类似的事情:
'''
<
%s
>
''' % (paragraph)
但这会破坏我的目的的可读性。
我还意识到我可以编写一些代码来将除第一行之外的所有行缩进 1 个缩进,但这并不是真正的可扩展解决方案(如果我有 2 个缩进怎么办?或 3 个缩进?等等)
编辑: 在发布答案之前,请考虑您的解决方案如何与以下内容配合使用:
'''
<
%s
<
%s
%s
<
%s
>
>
>
''' % (p1, p2, p3, p4)
How do I indent a multiline string in the context of string formatting? e.g.
'''
<
%s
>
''' % (paragraph)
where paragraph contains newlines. ('foo\nbar')
If I use the above code, I get output like this:
'''
<
foo
bar
>
'''
when I really want this:
'''
<
foo
bar
>
'''
I know I could do something like:
'''
<
%s
>
''' % (paragraph)
but this breaks readability for my purposes.
I also realize I could just write some code to indent all but the first line by 1 indent, but this isn't really an extensible solution (what if I have 2 indents? or 3? etc.)
EDIT:
Before you post an answer, consider how your solution works with something like this:
'''
<
%s
<
%s
%s
<
%s
>
>
>
''' % (p1, p2, p3, p4)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样:
结果:
.join()
方法中使用的字符串必须包含与之前的任何内容相同的空格(在开头加上
在你的字符串中。\n
) >%sHow about this:
Result:
The string used in the
.join()
method must contain the same whitespace (plus a\n
at the start) as whatever comes before%s
in your string.好吧,简单的不适合你的目的。您需要使用文档对象模型和具有适当缩进的展平系统。
或者,您可以做一些相当黑客的事情来检测每次替换之前的空格数量。这是非常脆弱的:
产量:
Okay, the simple doesn't suit your purposes. Either you need to use a document object model and a flattening system with appropriate indentation.
Or, you could do something fairly hacky to detect the amount of whitespace before each substitution. This is pretty fragile:
Yielding:
您不能指望 Python 解释器会自动缩进您的
段落
。你想让解释器弄乱你的数据吗? (提示:不。)你可以做的是注入空格:
但除非你绝对必须这样做,否则我会非常避免这样做,因为你不知道你可能正在处理哪些行结尾,并且通常感觉有点尴尬。
You can't expect the Python interpreter to automagically indent your
paragraph
. Would you want the interpreter messing around with your data? (Hint: NO.)What you can do is inject whitespace:
But I would very much refrain from that unless you absolutely have to, since you have no idea which line endings you might be dealing with, and generally feels kind of awkward.
Python 的 textwrap 模块是你的朋友,特别是它的
initial_indent
和 < code>subsequent_indent 参数。Python's textwrap module is your friend, especially its
initial_indent
andsubsequent_indent
parameters.