it will default to adding 'prefix' to all non-empty lines that do not
consist solely of whitespace characters.
"""
- if predicate is None:
- # str.splitlines(True) doesn't produce empty string.
- # ''.splitlines(True) => []
- # 'foo\n'.splitlines(True) => ['foo\n']
- # So we can use just `not s.isspace()` here.
- predicate = lambda s: not s.isspace()
-
prefixed_lines = []
- for line in text.splitlines(True):
- if predicate(line):
- prefixed_lines.append(prefix)
- prefixed_lines.append(line)
-
+ if predicate is None:
+ # str.splitlines(keepends=True) doesn't produce the empty string,
+ # so we need to use `str.isspace()` rather than a truth test.
+ # Inlining the predicate leads to a ~30% performance improvement.
+ for line in text.splitlines(True):
+ if not line.isspace():
+ prefixed_lines.append(prefix)
+ prefixed_lines.append(line)
+ else:
+ for line in text.splitlines(True):
+ if predicate(line):
+ prefixed_lines.append(prefix)
+ prefixed_lines.append(line)
return ''.join(prefixed_lines)