Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form. Note that tabs and spaces are both treated as whitespace, but t
(text)
| 414 | # -- Loosely related functionality ------------------------------------- |
| 415 | |
| 416 | def dedent(text): |
| 417 | """Remove any common leading whitespace from every line in `text`. |
| 418 | |
| 419 | This can be used to make triple-quoted strings line up with the left |
| 420 | edge of the display, while still presenting them in the source code |
| 421 | in indented form. |
| 422 | |
| 423 | Note that tabs and spaces are both treated as whitespace, but they |
| 424 | are not equal: the lines " hello" and "\\thello" are |
| 425 | considered to have no common leading whitespace. |
| 426 | |
| 427 | Entirely blank lines are normalized to a newline character. |
| 428 | """ |
| 429 | try: |
| 430 | lines = text.split('\n') |
| 431 | except (AttributeError, TypeError): |
| 432 | msg = f'expected str object, not {type(text).__qualname__!r}' |
| 433 | raise TypeError(msg) from None |
| 434 | |
| 435 | # Get length of leading whitespace, inspired by ``os.path.commonprefix()``. |
| 436 | non_blank_lines = [l for l in lines if l and not l.isspace()] |
| 437 | l1 = min(non_blank_lines, default='') |
| 438 | l2 = max(non_blank_lines, default='') |
| 439 | margin = 0 |
| 440 | for margin, c in enumerate(l1): |
| 441 | if c != l2[margin] or c not in ' \t': |
| 442 | break |
| 443 | |
| 444 | return '\n'.join([l[margin:] if not l.isspace() else '' for l in lines]) |
| 445 | |
| 446 | |
| 447 | def indent(text, prefix, predicate=None): |
searching dependent graphs…