|
| 1 | +def snake_to_camel_case(input: str, use_pascal: bool = False) -> str: |
| 2 | + """ |
| 3 | + Transforms a snake_case given string to camelCase (or PascalCase if indicated) |
| 4 | + (defaults to not use Pascal) |
| 5 | +
|
| 6 | + >>> snake_to_camel_case("some_random_string") |
| 7 | + 'someRandomString' |
| 8 | +
|
| 9 | + >>> snake_to_camel_case("some_random_string", use_pascal=True) |
| 10 | + 'SomeRandomString' |
| 11 | +
|
| 12 | + >>> snake_to_camel_case("some_random_string_with_numbers_123") |
| 13 | + 'someRandomStringWithNumbers123' |
| 14 | +
|
| 15 | + >>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True) |
| 16 | + 'SomeRandomStringWithNumbers123' |
| 17 | +
|
| 18 | + >>> snake_to_camel_case(123) |
| 19 | + Traceback (most recent call last): |
| 20 | + ... |
| 21 | + ValueError: Expected string as input, found <class 'int'> |
| 22 | +
|
| 23 | + >>> snake_to_camel_case("some_string", use_pascal="True") |
| 24 | + Traceback (most recent call last): |
| 25 | + ... |
| 26 | + ValueError: Expected boolean as use_pascal parameter, found <class 'str'> |
| 27 | + """ |
| 28 | + |
| 29 | + if not isinstance(input, str): |
| 30 | + raise ValueError(f"Expected string as input, found {type(input)}") |
| 31 | + if not isinstance(use_pascal, bool): |
| 32 | + raise ValueError( |
| 33 | + f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" |
| 34 | + ) |
| 35 | + |
| 36 | + words = input.split("_") |
| 37 | + |
| 38 | + start_index = 0 if use_pascal else 1 |
| 39 | + |
| 40 | + words_to_capitalize = words[start_index:] |
| 41 | + |
| 42 | + capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize] |
| 43 | + |
| 44 | + initial_word = "" if use_pascal else words[0] |
| 45 | + |
| 46 | + return "".join([initial_word] + capitalized_words) |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + from doctest import testmod |
| 51 | + |
| 52 | + testmod() |
0 commit comments