Skip to content

Instantly share code, notes, and snippets.

@huyx
Created December 20, 2013 02:23
Show Gist options
  • Save huyx/8049587 to your computer and use it in GitHub Desktop.
Save huyx/8049587 to your computer and use it in GitHub Desktop.
处理 docstring 缩进 参考: http://www.python.org/dev/peps/pep-0257/
# -*- coding: utf-8 -*-
import sys
def trim_docstring(docstring):
'''Handling Docstring Indentation
Reference:
- [PEP 257](http://www.python.org/dev/peps/pep-0257/) -- Docstring Conventions
'''
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment