我想在每行开头添加一些字符。
我该怎么做?
我曾这样做过:
'\n\t\t\t'.join(myStr.splitlines())
但这并不完美,我想知道是否有更好的方法。我最初想要自动缩进整个文本块。
我该怎么做?
我曾这样做过:
'\n\t\t\t'.join(myStr.splitlines())
但这并不完美,我想知道是否有更好的方法。我最初想要自动缩进整个文本块。
我认为这是一种相当不错的方法。你可以改进的一点是,你的方法会引入一个前导换行符,并且删除任何尾随的换行符。这样做不会:
'\t\t\t'.join(myStr.splitlines(True))
str.splitlines([keepends])
返回字符串中以行分隔符为边界拆分的行列表。此方法使用通用换行符方法来拆分行。除非给定并且为真,否则行结束符不包含在结果列表中。
此外,除非您的字符串以换行符开头,否则您不会在字符串开头添加任何制表符,因此您可能也需要这样做:
'\t\t\t'.join(('\n'+myStr.lstrip()).splitlines(True))
对于灵活的选项,您可能希望查看标准库中的textwrap。
示例:
>>> 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
非常灵活和有用。
编辑
如果您希望在使用textwrap时保留文本中的换行符含义,只需将textwrap与splitlines组合即可保持换行符不变。
悬挂缩进示例:
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.
str.splitlines
函数中添加True
参数,以便它保留换行符,并且我会从__future__
模块导入print
(对于不使用Python 3的人),这样您就可以指定将end
关键字设置为end =""
,以便Python的print
不会自动在末尾添加"\n"。我本来想修改您的答案,但恐怕我的编辑已被拒绝(真的不知道为什么)。 - jeromej