Remove repeating module names from string. Arguments: substr (str): The substring to remove repeating occurrences of. s (str): The string we want to work on. Example: >>> _shorten_names( ... 'x.tasks.add', ... 'x.tasks.add(2, 2) | x.tasks.add(
(substr: str, s: str)
| 157 | |
| 158 | |
| 159 | def remove_repeating(substr: str, s: str) -> str: |
| 160 | """Remove repeating module names from string. |
| 161 | |
| 162 | Arguments: |
| 163 | substr (str): The substring to remove repeating occurrences of. |
| 164 | s (str): The string we want to work on. |
| 165 | |
| 166 | Example: |
| 167 | |
| 168 | >>> _shorten_names( |
| 169 | ... 'x.tasks.add', |
| 170 | ... 'x.tasks.add(2, 2) | x.tasks.add(4) | x.tasks.mul(8)', |
| 171 | ... ) |
| 172 | 'x.tasks.add(2, 2) | add(4) | mul(8)' |
| 173 | """ |
| 174 | # find the first occurrence of substr in the string. |
| 175 | index = s.find(substr) |
| 176 | if index < 0: |
| 177 | return s |
| 178 | # leave the first occurrence of substr untouched. |
| 179 | head, rest = s[:index + len(substr)], s[index + len(substr):] |
| 180 | if substr not in rest: |
| 181 | return s |
| 182 | # strip seen substr from the rest of the string, but only where it starts |
| 183 | # a name (so ``app.`` is not removed from ``webapp.`` or ``my-app.``). |
| 184 | parts = rest.split(substr) |
| 185 | out = [parts[0]] |
| 186 | for i, part in enumerate(parts[1:]): |
| 187 | # character just before this occurrence in ``rest`` (none for the first |
| 188 | # occurrence when ``rest`` starts with it). |
| 189 | before = parts[i][-1:] or (substr[-1:] if i else '') |
| 190 | out.append(substr + part if before.isalnum() or before in ('_', '.', '-') else part) |
| 191 | return head + ''.join(out) |
| 192 | |
| 193 | |
| 194 | StringIO = io.StringIO |
no test coverage detected