Indent a string.
1 2 | def indent(txt, stops=1):
return '\n'.join(" " * 4 * stops + line for line in txt.splitlines())
|
Tags: indent
Indent a string.
1 2 | def indent(txt, stops=1):
return '\n'.join(" " * 4 * stops + line for line in txt.splitlines())
|
" " * 4 could usefully be replaced by a single string with 4 spaces. This would be simpler and faster.
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.
Not exactly the same, but look at the textwrap module.