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 w
(text, prefix, predicate=None)
| 445 | |
| 446 | |
| 447 | def indent(text, prefix, predicate=None): |
| 448 | """Adds 'prefix' to the beginning of selected lines in 'text'. |
| 449 | |
| 450 | If 'predicate' is provided, 'prefix' will only be added to the lines |
| 451 | where 'predicate(line)' is True. If 'predicate' is not provided, |
| 452 | it will default to adding 'prefix' to all non-empty lines that do not |
| 453 | consist solely of whitespace characters. |
| 454 | """ |
| 455 | prefixed_lines = [] |
| 456 | if predicate is None: |
| 457 | # str.splitlines(keepends=True) doesn't produce the empty string, |
| 458 | # so we need to use `str.isspace()` rather than a truth test. |
| 459 | # Inlining the predicate leads to a ~30% performance improvement. |
| 460 | for line in text.splitlines(True): |
| 461 | if not line.isspace(): |
| 462 | prefixed_lines.append(prefix) |
| 463 | prefixed_lines.append(line) |
| 464 | else: |
| 465 | for line in text.splitlines(True): |
| 466 | if predicate(line): |
| 467 | prefixed_lines.append(prefix) |
| 468 | prefixed_lines.append(line) |
| 469 | return ''.join(prefixed_lines) |
| 470 | |
| 471 | |
| 472 | if __name__ == "__main__": |
searching dependent graphs…