如何缩进多行字符串的内容?

发布于 2024-12-17 15:42:53 字数 207 浏览 2 评论 0原文

我正在使用 python cog 模块生成 C++ 样板代码,到目前为止效果很好,但是我唯一担心的是生成的代码本身就很难看,而且由于它没有缩进,所以变得更糟。我懒得在字符串生成函数中得到正确的缩进,所以我想知道是否有一个Python util函数来缩进多行字符串的内容?

I'm using the python cog module to generate C++ boilerplate code, and it is working great so far, but my only concern is that the resulting code, which is ugly by itself, is made worse by the fact that it's not indented. I'm too lazy to get the indentation right in the string generation function, so I'm wondering if there is a Python util function to indent the content of a multi-line string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

路弥 2024-12-24 15:42:53

您只需用适当数量的填充字符填充每一行即可缩进字符串中的行。这可以通过使用 textwrap.indent()< 轻松完成/code>函数是在 Python 3.3 中添加到模块中的。或者,您可以使用下面的代码,该代码也适用于早期的 Python 版本。

try:
    import textwrap
    textwrap.indent
except AttributeError:  # undefined function (wasn't added until Python 3.3)
    def indent(text, amount, ch=' '):
        padding = amount * ch
        return ''.join(padding+line for line in text.splitlines(True))
else:
    def indent(text, amount, ch=' '):
        return textwrap.indent(text, amount * ch)

text = '''\
And the Lord God said unto the serpent,
Because thou hast done this, thou art
cursed above all cattle, and above every
beast of the field; upon thy belly shalt
thou go, and dust shalt thou eat all the
days of thy life: And I will put enmity
between thee and the woman, and between
thy seed and her seed; it shall bruise
thy head, and thou shalt bruise his
heel.

3:15-King James
'''

print('Text indented 4 spaces:\n')
print(indent(text, 4))

结果:

Text indented 4 spaces:

    And the Lord God said unto the serpent,
    Because thou hast done this, thou art
    cursed above all cattle, and above every
    beast of the field; upon thy belly shalt
    thou go, and dust shalt thou eat all the
    days of thy life: And I will put enmity
    between thee and the woman, and between
    thy seed and her seed; it shall bruise
    thy head, and thou shalt bruise his
    heel.

    3:15-King James

You can indent the lines in a string by just padding each one with proper number of pad characters. This can easily be done by using the textwrap.indent() function which was added to the module in Python 3.3. Alternatively you could use the code below which will also work in earlier Python versions.

try:
    import textwrap
    textwrap.indent
except AttributeError:  # undefined function (wasn't added until Python 3.3)
    def indent(text, amount, ch=' '):
        padding = amount * ch
        return ''.join(padding+line for line in text.splitlines(True))
else:
    def indent(text, amount, ch=' '):
        return textwrap.indent(text, amount * ch)

text = '''\
And the Lord God said unto the serpent,
Because thou hast done this, thou art
cursed above all cattle, and above every
beast of the field; upon thy belly shalt
thou go, and dust shalt thou eat all the
days of thy life: And I will put enmity
between thee and the woman, and between
thy seed and her seed; it shall bruise
thy head, and thou shalt bruise his
heel.

3:15-King James
'''

print('Text indented 4 spaces:\n')
print(indent(text, 4))

Result:

Text indented 4 spaces:

    And the Lord God said unto the serpent,
    Because thou hast done this, thou art
    cursed above all cattle, and above every
    beast of the field; upon thy belly shalt
    thou go, and dust shalt thou eat all the
    days of thy life: And I will put enmity
    between thee and the woman, and between
    thy seed and her seed; it shall bruise
    thy head, and thou shalt bruise his
    heel.

    3:15-King James
长途伴 2024-12-24 15:42:53

如果您有一个前导换行符:

Heredocs 可以包含一个文字换行符,或者您可以在前面添加一个换行符。

indent = '    '

indent_me = '''
Hello
World
''' 
indented = indent_me.replace('\n', '\n' + indent)
print(indented)

这是 pprint 转储中显示的:

>>> pprint(缩进)

'你好\n世界\n'

笨拙,但有效


如果您没有前导换行符:

indent = '    '

indent_me = '''\
Hello
World
''' 
indented = indent + indent_me.replace('\n', '\n' + indent)
print(indented)

可选,修剪第一个换行符和尾随空格/制表符

.lstrip('\n').rstrip(' \t')

If you have a leading newline:

Heredocs can contain a literal newline, or you can prepend one.

indent = '    '

indent_me = '''
Hello
World
''' 
indented = indent_me.replace('\n', '\n' + indent)
print(indented)

Here is it shown in pprint dump:

>>> pprint(indented)

' Hello\n World\n '

Awkward, but works


If you do not have a leading newline:

indent = '    '

indent_me = '''\
Hello
World
''' 
indented = indent + indent_me.replace('\n', '\n' + indent)
print(indented)

Optional, trim first newline and trailing spaces/tabs

.lstrip('\n').rstrip(' \t')
善良天后 2024-12-24 15:42:53

为什么不通过命令行代码格式化程序(例如 astyle)管道输出?

Why not pipe the output through a command-line code formatter such as astyle?

七色彩虹 2024-12-24 15:42:53

python Tools/Scripts/ 目录中有一个脚本,主要用于修复整个 python 文件的缩进。但是,您可以轻松地稍微调整脚本并将其应用于代码段/行或其他类型的文件。

该脚本也可以在线找到,此处:
http://svn.python.org/projects/python/trunk /Tools/scripts/reindent.py

或者,作为此处的模块:
http://pypi.python.org/pypi/Reindent/0.1.0

There is a script located in the python Tools/Scripts/ directory which is primarily for fixing the indentation of entire python files. However, you can easily tweak the script a little and apply it to sections/lines of code, or other types of files.

The script is also located online, here:
http://svn.python.org/projects/python/trunk/Tools/scripts/reindent.py

Or, as a module here:
http://pypi.python.org/pypi/Reindent/0.1.0

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