From 6118b05f0efd1c2839eb8bc4de36723af1fcc364 Mon Sep 17 00:00:00 2001 From: Carlos Villar Date: Thu, 13 Oct 2022 08:24:53 +0200 Subject: [PATCH] Convert snake_case to camelCase or PascalCase (#7028) (#7034) * Added snake_case to Camel or Pascal case Fixes: #7028 * Added suggested changes * Add ending empty line from suggestion Co-authored-by: Caeden * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update strings/snake_case_to_camel_pascal_case.py Co-authored-by: Christian Clauss Co-authored-by: Caeden Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss --- strings/snake_case_to_camel_pascal_case.py | 52 ++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 strings/snake_case_to_camel_pascal_case.py diff --git a/strings/snake_case_to_camel_pascal_case.py b/strings/snake_case_to_camel_pascal_case.py new file mode 100644 index 000000000..7b2b61d1d --- /dev/null +++ b/strings/snake_case_to_camel_pascal_case.py @@ -0,0 +1,52 @@ +def snake_to_camel_case(input: str, use_pascal: bool = False) -> str: + """ + Transforms a snake_case given string to camelCase (or PascalCase if indicated) + (defaults to not use Pascal) + + >>> snake_to_camel_case("some_random_string") + 'someRandomString' + + >>> snake_to_camel_case("some_random_string", use_pascal=True) + 'SomeRandomString' + + >>> snake_to_camel_case("some_random_string_with_numbers_123") + 'someRandomStringWithNumbers123' + + >>> snake_to_camel_case("some_random_string_with_numbers_123", use_pascal=True) + 'SomeRandomStringWithNumbers123' + + >>> snake_to_camel_case(123) + Traceback (most recent call last): + ... + ValueError: Expected string as input, found + + >>> snake_to_camel_case("some_string", use_pascal="True") + Traceback (most recent call last): + ... + ValueError: Expected boolean as use_pascal parameter, found + """ + + if not isinstance(input, str): + raise ValueError(f"Expected string as input, found {type(input)}") + if not isinstance(use_pascal, bool): + raise ValueError( + f"Expected boolean as use_pascal parameter, found {type(use_pascal)}" + ) + + words = input.split("_") + + start_index = 0 if use_pascal else 1 + + words_to_capitalize = words[start_index:] + + capitalized_words = [word[0].upper() + word[1:] for word in words_to_capitalize] + + initial_word = "" if use_pascal else words[0] + + return "".join([initial_word] + capitalized_words) + + +if __name__ == "__main__": + from doctest import testmod + + testmod()