简体   繁体   English

每行缩进打印

[英]Printing with indenting every line

Is there a way in python to print something, say foo = "The Title of The Message\n\tThe first paragraph of the message" with a tab appended to each line, without modifiying my variable, ( foo in this example). python 中有没有办法打印一些东西,比如foo = "The Title of The Message\n\tThe first paragraph of the message" ,每行都附加一个制表符,而不修改我的变量(本例中为foo )。

The result I want would be: The Title of The Message The first paragraph of the message"我想要的结果是: The Title of The Message The first paragraph of the message"

I'm looking for something similar to when you do a git log , the message of the commit is always indented我正在寻找类似于您执行git log时的内容,提交的消息总是缩进

I'm not quite sure what you expect here. 我不太确定您在这里的期望。 No, there isn't an automatic formatting tool to do this. 不,没有自动格式化工具可以执行此操作。 However, you can certainly copy the value and modify that , or print an in-line alteration. 但是,你当然可以复制的价值和修改 ,或打印在线改变。 For instance: 例如:

print foo.replace("\n", "\n\t")

string.replace returns an altered copy of the string. string.replace返回更改后的字符串副本。

Don't know of any builtins / standard ways of doing it, but you could do a single tab with Prune's simple solution ( print foo.replace('\\n', '\\n\\t') ), or if you want it more general for any number of leading tabs: 不知道任何内置方法/标准方法,但是您可以使用Prune的简单解决方案print foo.replace('\\n', '\\n\\t') )创建单个选项卡,或者如果需要对于任何数量的前导标签,它都更为通用:

>>> def print_indented(n, s):
...     """Print a string `s` indented with `n` tabs at each newline"""
...     for x in s.split('\n'):
...         print '\t'*n + x
...
>>> foo = "The Title of The Message\n\tThe first paragraph of the message"
>>> print_indented(1, foo)
        The Title of The Message
                The first paragraph of the message
>>> print_indented(2, foo)
                The Title of The Message
                        The first paragraph of the message

The '\\t'*n bit repeats the tab character n times. '\\t'*n位将制表符字符重复n次。

This can now be done with the textwrap module, specifically itsindent function.这现在可以通过textwrap模块完成,特别是它的indent function。

Example:例子:

import textwrap


foo = "The Title of The Message\n\tThe first paragraph of the message"
print(textwrap.indent(foo, '\t'))

Output: Output:

        The Title of The Message
                The first paragraph of the message

There is an optional predicate argument which can be used to control which lines are indented, eg you might want to ignore empty lines and whitespace-only lines to not add unnecessary extra spaces.有一个可选的predicate参数可用于控制缩进的行,例如,您可能希望忽略空行和仅空白行,以免添加不必要的额外空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM