Đối với linh hoạt tùy chọn, bạn có thể muốn xem textwrap trong thư viện chuẩn.
Ví dụ:
>>> 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
Bạn có thể thấy rằng bạn có thể không chỉ dễ dàng thêm không gian linh hoạt trên mặt trước của mỗi dòng, bạn có thể cắt mỗi dòng để phù hợp với, làm dấu ngang giữa hai chữ, mở rộng các tab vv
Nó sẽ quấn (do đó tên) dòng trở nên quá dài vì các bổ sung ở phía trước:
>>> 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
Rất linh hoạt và hữu ích.
Sửa
Nếu bạn muốn giữ lại ý nghĩa của kết thúc dòng trong văn bản với textwrap, chỉ cần kết hợp với textwrap splitlines để giữ dòng kết thúc giống nhau.
Ví dụ về treo thụt lề:
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
in
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.
Tôi đã không biết rằng, cảm ơn! – JeromeJ