Welcome, guest | Sign In | My Account | Store | Cart

Indent a string.

Python, 2 lines
1
2
def indent(txt, stops=1):
    return '\n'.join(" " * 4 * stops + line for line in  txt.splitlines())

3 comments

Eric-Olivier LE BIGOT 14 years, 8 months ago  # | flag

" " * 4 could usefully be replaced by a single string with 4 spaces. This would be simpler and faster.

Charlie Clark 14 years, 8 months ago  # | flag

I'm trying to think of the use case for this over says expandtabs. But a couple of comments: if this is a long text avoid creating new strings by and do you really need a list?

As Eric points out " " * 4 * stops will run for each line of your original string. Easier to create it just once.

If you use a generator you can avoid using an intermediate list as, if you are indenting, you probably want to print the indented text. Below is an example that should, in theory, run a lot faster. In practice you'll only notice for extremely long texts.

def indent(txt, stops=1):
    spacer = "\t".expandtabs(4) * stops
    for line in txt.splitlines():
        yield "%s%s" % (spacer, line)

for l in indent(sample):
    print l
Gabriel Genellina 14 years, 8 months ago  # | flag

Not exactly the same, but look at the textwrap module.

Created by tat.wright on Wed, 5 Aug 2009 (MIT)
Python recipes (4591)
tat.wright's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks