在每个lin的开头添加一些字符

2024-10-01 11:34:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在每行的开头加上一些字符。

我该怎么办?

我是这么做的:

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

但这并不完美,我想知道是否有更好的方法来做到这一点。我本来想自动缩进一整块文本。


Tags: 方法文本字符joinmystrsplitlines
2条回答

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

非常灵活和有用。

编辑

如果你想用文本换行来保持文本中行结束的含义,只需把文本换行和拆分行结合起来,以保持行结束相同。

悬挂缩进示例:

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.

我觉得那是个很好的方法。您可以改进的一件事是,您的方法引入了一个前置换行符,并删除了任何后续换行符。这不会:

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

From the docs:

str.splitlines([keepends])

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.

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

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

相关问题 更多 >