在每行开头添加一些字符

11
我想在每行开头添加一些字符。
我该怎么做?
我曾这样做过:
'\n\t\t\t'.join(myStr.splitlines())
但这并不完美,我想知道是否有更好的方法。我最初想要自动缩进整个文本块。
2个回答

18

我认为这是一种相当不错的方法。你可以改进的一点是,你的方法会引入一个前导换行符,并且删除任何尾随的换行符。这样做不会:

'\t\t\t'.join(myStr.splitlines(True))

文档中的描述:

str.splitlines([keepends])

返回字符串中以行分隔符为边界拆分的行列表。此方法使用通用换行符方法来拆分行。除非给定并且为真,否则行结束符不包含在结果列表中。

此外,除非您的字符串以换行符开头,否则您不会在字符串开头添加任何制表符,因此您可能也需要这样做:

'\t\t\t'.join(('\n'+myStr.lstrip()).splitlines(True))

4

对于灵活的选项,您可能希望查看标准库中的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.

(2)或者这完全没用,最好在所有地方只使用“\n”? - jeromej
@JeromeJ:你为什么说这个没用?textwrap.py 的功能并不是微不足道的。想一想文字处理器中的自动换行。如果你在每行前面添加了三个制表符,那么当有一行过长无法在给定的空间中显示时会发生什么?这个库允许你在每行开头添加空格,并在该空格使行过宽时将所有其余行包装起来。这有什么作用呢? - dawg
啊,不是这个意思,我是在谈论我的评论(但我不能再编辑它了,太晚了):也许想要保留新行分隔符类型是无用的,我最好只使用“\n”来换行(这是第二个问题)。关于换行功能,我不需要它(我猜可以禁用它),我只需要在其前面添加东西,但我可以看到模块有多么强大(如果您关心换行长行,那就更加强大了)。 - jeromej
感谢您的编辑,但我会在str.splitlines函数中添加True参数,以便它保留换行符,并且我会从__future__模块导入print(对于不使用Python 3的人),这样您就可以指定将end关键字设置为end ="",以便Python的print不会自动在末尾添加"\n"。我本来想修改您的答案,但恐怕我的编辑已被拒绝(真的不知道为什么)。 - jeromej
我现在还不太自信使用textwrap。非常感谢您的答案,虽然它非常有帮助☺ 我最终会回过头来看的。 - jeromej
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接