Recursively replaces substrings in a value. Replaces all substrings of the "search_for" with "replace_with" for all strings occurring in "values". This is done by recursively iterating into lists as well as the keys and values of dictionaries.
(values, search_for, replace_with)
| 252 | |
| 253 | |
| 254 | def ReplaceSubstrings(values, search_for, replace_with): |
| 255 | """Recursively replaces substrings in a value. |
| 256 | Replaces all substrings of the "search_for" with "replace_with" for all |
| 257 | strings occurring in "values". This is done by recursively iterating into |
| 258 | lists as well as the keys and values of dictionaries.""" |
| 259 | if isinstance(values, str): |
| 260 | return values.replace(search_for, replace_with) |
| 261 | |
| 262 | if isinstance(values, list): |
| 263 | result = [] |
| 264 | for v in values: |
| 265 | # Remove the item from list for complete match. |
| 266 | if v == search_for and replace_with == '': |
| 267 | continue |
| 268 | result.append(ReplaceSubstrings(v, search_for, replace_with)) |
| 269 | return result |
| 270 | |
| 271 | if isinstance(values, dict): |
| 272 | # For dictionaries, do the search for both the key and values. |
| 273 | result = {} |
| 274 | for key, value in values.items(): |
| 275 | new_key = ReplaceSubstrings(key, search_for, replace_with) |
| 276 | new_value = ReplaceSubstrings(value, search_for, replace_with) |
| 277 | result[new_key] = new_value |
| 278 | return result |
| 279 | |
| 280 | # Assume everything else is unchanged. |
| 281 | return values |
| 282 | |
| 283 | |
| 284 | def DeduplicateLists(values): |