Python 块格式化

发布于 2024-12-19 05:57:17 字数 694 浏览 1 评论 0原文

如何在字符串格式化上下文中缩进多行字符串?例如

'''
<
     %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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

野稚 2024-12-26 05:57:17

怎么样:

'''
<
   %s
>
''' % ("\n   ".join(paragraph.split("\n")))

结果:

<
   foo
   bar
>

.join() 方法中使用的字符串必须包含与 之前的任何内容相同的空格(在开头加上 \n) >%s 在你的字符串中。

How about this:

'''
<
   %s
>
''' % ("\n   ".join(paragraph.split("\n")))

Result:

<
   foo
   bar
>

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.

终陌 2024-12-26 05:57:17

好吧,简单的不适合你的目的。您需要使用文档对象模型和具有适当缩进的展平系统。

或者,您可以做一些相当黑客的事情来检测每次替换之前的空格数量。这是非常脆弱的:

import re

def ind_sbt(text,indent='\t'):
    return text.replace('\n','\n%s' % (indent,))

def adjust_indents(fmtstr,*args):
    """Hacky, crude detection of identation level"""
    indented_substitutions = re.compile(r'\n(\s+)%s')
    return fmtstr % tuple([ ind_sbt(arg,indent=i) for (arg,i) in zip(args,indented_substitutions.findall(fmtstr))])

p1 = p2 = p3 = p4 = "foo\nbar"

print adjust_indents('''
<
    %s
    <
        %s
        %s
        <
            %s
        >
    >
>
''',p1,p2,p3,p4)

产量:

<
        foo
        bar
        <
                foo
                bar
                foo
                bar
                <
                        foo
                        bar
                >
        >
>

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:

import re

def ind_sbt(text,indent='\t'):
    return text.replace('\n','\n%s' % (indent,))

def adjust_indents(fmtstr,*args):
    """Hacky, crude detection of identation level"""
    indented_substitutions = re.compile(r'\n(\s+)%s')
    return fmtstr % tuple([ ind_sbt(arg,indent=i) for (arg,i) in zip(args,indented_substitutions.findall(fmtstr))])

p1 = p2 = p3 = p4 = "foo\nbar"

print adjust_indents('''
<
    %s
    <
        %s
        %s
        <
            %s
        >
    >
>
''',p1,p2,p3,p4)

Yielding:

<
        foo
        bar
        <
                foo
                bar
                foo
                bar
                <
                        foo
                        bar
                >
        >
>
意中人 2024-12-26 05:57:17

您不能指望 Python 解释器会自动缩进您的段落。你想让解释器弄乱你的数据吗? (提示:不。)

你可以做的是注入空格:

'''
<
    %s
>
''' % (paragraph.replace('\n','\n    ')) # assuming 4 space soft tabs

但除非你绝对必须这样做,否则我会非常避免这样做,因为你不知道你可能正在处理哪些行结尾,并且通常感觉有点尴尬。

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:

'''
<
    %s
>
''' % (paragraph.replace('\n','\n    ')) # assuming 4 space soft tabs

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.

酷遇一生 2024-12-26 05:57:17

Python 的 textwrap 模块是你的朋友,特别是它的 initial_indent 和 < code>subsequent_indent 参数。

Python's textwrap module is your friend, especially its initial_indent and subsequent_indent parameters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文