>>> hamlet='''\
... To be, or not to be: that is the question:
... Whether 'tis nobler in the mind to suffer
... The slings and arrows of outrageous fortune,
... Or to take arms against a sea of troubles,
... And by opposing end them? To die: to sleep;
... No more; and by a sleep to say we end
... '''
>>> import textwrap
>>> wrapper=textwrap.TextWrapper(initial_indent='\t', subsequent_indent='\t'*2)
>>> print wrapper.fill(hamlet)
To be, or not to be: that is the question: Whether 'tis nobler in the
mind to suffer The slings and arrows of outrageous fortune, Or to
take arms against a sea of troubles, And by opposing end them? To
die: to sleep; No more; and by a sleep to say we end
>>> wrapper=textwrap.TextWrapper(initial_indent='\t'*3,
... subsequent_indent='\t'*4, width=40)
>>> print wrapper.fill(hamlet)
To be, or not to be: that is the
question: Whether 'tis nobler in the
mind to suffer The slings and arrows
of outrageous fortune, Or to take
arms against a sea of troubles, And
by opposing end them? To die: to
sleep; No more; and by a sleep to
say we end
非常灵活和有用。
编辑
如果你想用文本换行来保持文本中行结束的含义,只需把文本换行和拆分行结合起来,以保持行结束相同。
悬挂缩进示例:
import textwrap
hamlet='''\
Hamlet: In the secret parts of Fortune? O, most true! She is a strumpet. What's the news?
Rosencrantz: None, my lord, but that the world's grown honest.
Hamlet: Then is doomsday near.'''
wrapper=textwrap.TextWrapper(initial_indent='\t'*1,
subsequent_indent='\t'*3,
width=30)
for para in hamlet.splitlines():
print wrapper.fill(para)
print
印刷品
Hamlet: In the secret parts
of Fortune? O, most true!
She is a strumpet. What's
the news?
Rosencrantz: None, my lord,
but that the world's grown
honest.
Hamlet: Then is doomsday
near.
Return a list of the lines in the string,
breaking at line boundaries. This method uses the universal newlines
approach to splitting lines. Line breaks are not included in the
resulting list unless keepends is given and true.
对于灵活的选项,您可能希望查看标准库中的textwrap。
示例:
您可以看到,您不仅可以轻松地在每一行的前面添加灵活的空间,还可以对每一行进行裁剪以适应、断字、展开制表符等
它将换行(因此命名)因为前面的添加而变得太长:
非常灵活和有用。
编辑
如果你想用文本换行来保持文本中行结束的含义,只需把文本换行和拆分行结合起来,以保持行结束相同。
悬挂缩进示例:
印刷品
我觉得那是个很好的方法。您可以改进的一件事是,您的方法引入了一个前置换行符,并删除了任何后续换行符。这不会:
From the docs:
此外,除非字符串以换行符开头,否则不会在字符串开头添加任何制表符,因此您可能也希望这样做:
相关问题 更多 >
编程相关推荐