Skip to content

Commit 6118b05

Browse files
carlos3dxCaedenPHpre-commit-ci[bot]cclauss
authored
Convert snake_case to camelCase or PascalCase (TheAlgorithms#7028) (TheAlgorithms#7034)
* Added snake_case to Camel or Pascal case Fixes: TheAlgorithms#7028 * Added suggested changes * Add ending empty line from suggestion Co-authored-by: Caeden <[email protected]> * [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 <[email protected]> Co-authored-by: Caeden <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <[email protected]>
1 parent 1aa7bd9 commit 6118b05

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)