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

时间:2013-08-22 19:40:55

标签: python string indentation

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

我该怎么办?

我这样做:

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

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

2 个答案:

答案 0 :(得分:14)

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

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

From the docs:

  

str.splitlines([keepends])

     
    

返回字符串中的行列表,     突破线边界。此方法使用通用换行符     分裂线的方法。换行符不包括在内     结果列表,除非给出了keepends并且为真。

  

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

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

答案 1 :(得分:1)

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