string - Strip common indentation from the beginning of each line similar to what pydoc help does with docstrings -
i have module foo
(in foo.py) function f
defined in manner.
def f(): """test line 1 line 2 """ pass
this how docstring appears in interactive session.
>>> print(foo.f.__doc__) test line 1 line 2 >>> help(foo.f) on function f in module foo: f() test line 1 line 2 >>>
as, can see help()
function takes care of removing common indentation beginning of each line while displaying help. want write own function similar.
for example, if
s = """foo line 1 line 2 line 3 """
then my_function(s)
should return
"""foo line 1 line 2 line 3"""
is there in python standard library can me this?
you use textwrap.dedent()
:
import textwrap def my_function(s): first, *rest = s.splitlines(keepends=true) # first line special return first + textwrap.dedent(''.join(rest))
example:
>>> my_function(s) 'foo\n\nline 1\nline 2\nline 3\n'
note: final newline not stripped.
Comments
Post a Comment