forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake_case_to_camel_pascal_case.py
52 lines (36 loc) · 1.58 KB
/
snake_case_to_camel_pascal_case.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
defsnake_to_camel_case(input_str: 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 <class 'int'>
>>> snake_to_camel_case("some_string", use_pascal="True")
Traceback (most recent call last):
...
ValueError: Expected boolean as use_pascal parameter, found <class 'str'>
"""
ifnotisinstance(input_str, str):
msg=f"Expected string as input, found {type(input_str)}"
raiseValueError(msg)
ifnotisinstance(use_pascal, bool):
msg=f"Expected boolean as use_pascal parameter, found {type(use_pascal)}"
raiseValueError(msg)
words=input_str.split("_")
start_index=0ifuse_pascalelse1
words_to_capitalize=words[start_index:]
capitalized_words= [word[0].upper() +word[1:] forwordinwords_to_capitalize]
initial_word=""ifuse_pascalelsewords[0]
return"".join([initial_word, *capitalized_words])
if__name__=="__main__":
fromdoctestimporttestmod
testmod()