11

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

我该怎么办?

我正在这样做:

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

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

4

2 回答 2

19

我认为这是一个非常好的方法。您可以改进的一件事是您的方法引入了前导换行符,并删除了任何尾随换行符。这不会:

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

从文档:

str.splitlines([保持])

返回字符串中的行列表,在行边界处中断。此方法使用通用换行方法来分割行。换行符不包含在结果列表中,除非给出了 keepends 并且为真。

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

'\t\t\t'.join(('\n'+myStr.lstrip()).splitlines(True))
于 2013-08-22T19:44:07.390 回答
3

对于灵活的选择,您可能希望查看标准库中的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.
于 2013-08-22T20:12:46.030 回答