Apply a transformer function to all strings in a nested data structure. :param data: The data structure (dict, list, nested dicts) to transform. :param transformer: A function that takes a string and returns a transformed string. :return: The transformed data structure.
(data, transformer)
| 1 | |
| 2 | |
| 3 | def applyTransformer(data, transformer): |
| 4 | """ |
| 5 | Apply a transformer function to all strings in a nested data structure. |
| 6 | |
| 7 | :param data: The data structure (dict, list, nested dicts) to transform. |
| 8 | :param transformer: A function that takes a string and returns a transformed string. |
| 9 | :return: The transformed data structure. |
| 10 | """ |
| 11 | if isinstance(data, dict): |
| 12 | # If the item is a dictionary, apply the transformer to each value. |
| 13 | return {key: applyTransformer(value, transformer) for key, value in data.items()} |
| 14 | elif isinstance(data, list): |
| 15 | # If the item is a list, apply the transformer to each element. |
| 16 | return [applyTransformer(element, transformer) for element in data] |
| 17 | elif isinstance(data, str): |
| 18 | # If the item is a string, apply the transformer directly. |
| 19 | return transformer(data) |
| 20 | else: |
| 21 | # If the item is not a dict, list, or string, return it as is. |
| 22 | return data |
| 23 | |
| 24 | def asteriskText(inp): |
| 25 | from random import randint |
no test coverage detected