Returns a string with consecutive spaces collapsed to a single space. Whitespace on empty lines and at the end of each line is removed. With indentation=True, retains leading whitespace on each line.
(string, indentation=False, replace=" ")
| 846 | RE_TABS = re.compile(r"\t+", re.M) # Matches one or more tabs. |
| 847 | |
| 848 | def collapse_spaces(string, indentation=False, replace=" "): |
| 849 | """ Returns a string with consecutive spaces collapsed to a single space. |
| 850 | Whitespace on empty lines and at the end of each line is removed. |
| 851 | With indentation=True, retains leading whitespace on each line. |
| 852 | """ |
| 853 | p = [] |
| 854 | for x in string.splitlines(): |
| 855 | n = indentation and len(x) - len(x.lstrip()) or 0 |
| 856 | p.append(x[:n] + RE_SPACES.sub(replace, x[n:]).strip()) |
| 857 | return "\n".join(p) |
| 858 | |
| 859 | def collapse_tabs(string, indentation=False, replace=" "): |
| 860 | """ Returns a string with (consecutive) tabs replaced by a single space. |