在 python 中使用缩进打印 [英] Printing with indentation in python

查看:37
本文介绍了在 python 中使用缩进打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法打印以下内容,

is there a way to print the following,

print user + ":\t\t" + message

这样比终端长度更宽的冗长消息总是换行(从同一位置开始)?所以例如这个

so that lengthy messages that are wider than the length of the terminal always wraps (starts from the same position) ? so for example this

Username:              LEFTLEFTLEFTLEFTLEFTLEFTLEFT
RIGHTRIGHTRIGHT

应该变成

Username:              LEFTLEFTLEFTLEFTLEFTLEFTLEFT
                       RIGHTRIGHTRIGHT

推荐答案

我认为您在这里寻找的是 textwrap 模块:

I think what you're looking for here is the textwrap module:

user = "Username"
prefix = user + ": "
preferredWidth = 70
wrapper = textwrap.TextWrapper(initial_indent=prefix, width=preferredWidth,
                               subsequent_indent=' '*len(prefix))
message = "LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT " * 3
print wrapper.fill(message)

打印:

Username: LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT
          LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT
          LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT

<小时>

如果您真的想在缩进中使用制表符,那就有点棘手了,因为您必须首先对 initial_indent 进行制表符展开以找出正确的 subsequent_indent用.而且,因为您的前缀实际上以两个标签结束,所以它更加复杂.这是我想出的最简单的:


If you actually want to use tabs in the indent, that's a little trickier, because you have to first tab-expand the initial_indent to figure out the correct subsequent_indent to use. And, because your prefix actually ends with two tabs, it's even more complicated. Here's the simplest I've come up with:

user = "Username"
prefix = user + ":\t\t"
expanded_indent = textwrap.fill(prefix+'$', replace_whitespace=False)[:-1]
subsequent_indent = ' ' * len(expanded_indent)
wrapper = textwrap.TextWrapper(initial_indent=prefix,
                               subsequent_indent=subsequent_indent)
message = "LEFTLEFTLEFTLEFTLEFTLEFTLEFT RIGHTRIGHTRIGHT " * 3
print wrapper.fill(message)

如果您重复执行此操作,您可能希望将这些乱七八糟的东西包装在一个函数中.

If you do this repeatedly, you will probably want to wrap that mess up in a function.

这篇关于在 python 中使用缩进打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆