mirror of
https://github.com/python/cpython.git
synced 2025-12-15 21:44:50 +00:00
Close #13857: Added textwrap.indent() function (initial patch by Ezra
Berch)
This commit is contained in:
parent
3c4acd8bf9
commit
4fae8cdaea
6 changed files with 201 additions and 7 deletions
|
|
@ -7,7 +7,7 @@
|
|||
|
||||
import re
|
||||
|
||||
__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent']
|
||||
__all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent']
|
||||
|
||||
# Hardcode the recognized whitespace characters to the US-ASCII
|
||||
# whitespace characters. The main reason for doing this is that in
|
||||
|
|
@ -386,6 +386,25 @@ def dedent(text):
|
|||
text = re.sub(r'(?m)^' + margin, '', text)
|
||||
return text
|
||||
|
||||
|
||||
def indent(text, prefix, predicate=None):
|
||||
"""Adds 'prefix' to the beginning of selected lines in 'text'.
|
||||
|
||||
If 'predicate' is provided, 'prefix' will only be added to the lines
|
||||
where 'predicate(line)' is True. If 'predicate' is not provided,
|
||||
it will default to adding 'prefix' to all non-empty lines that do not
|
||||
consist solely of whitespace characters.
|
||||
"""
|
||||
if predicate is None:
|
||||
def predicate(line):
|
||||
return line.strip()
|
||||
|
||||
def prefixed_lines():
|
||||
for line in text.splitlines(True):
|
||||
yield (prefix + line if predicate(line) else line)
|
||||
return ''.join(prefixed_lines())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
#print dedent("\tfoo\n\tbar")
|
||||
#print dedent(" \thello there\n \t how are you?")
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue