Skip to content

Commit 4b978dc

Browse files
committed
feat(day 114): add camelCase to snake_case converter with regex option
1 parent 3fbdce6 commit 4b978dc

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
3+
Camel to Snake
4+
Given a string in camel case, return the snake case version of the string using the following rules:
5+
6+
The input string will contain only letters (A-Z and a-z) and will always start with a lowercase letter.
7+
Every uppercase letter in the camel case string starts a new word.
8+
Convert all letters to lowercase.
9+
Separate words with an underscore (_).
10+
"""
11+
12+
import unittest
13+
14+
class CamelToSnakeTest(unittest.TestCase):
15+
16+
def test1(self):
17+
self.assertEqual(to_snake("helloWorld"),"hello_world")
18+
19+
def test2(self):
20+
self.assertEqual(to_snake("myVariableName"),"my_variable_name")
21+
22+
def test3(self):
23+
self.assertEqual(to_snake("freecodecampDailyChallenges"),"freecodecamp_daily_challenges")
24+
25+
26+
def to_snake(camel):
27+
28+
snake = ''
29+
30+
for char in camel:
31+
if char.isupper():
32+
snake += '_'+char.lower()
33+
else:
34+
snake += char
35+
36+
return snake
37+
38+
import re
39+
def to_snake_optimized(camel):
40+
# Insert underscore before each uppercase letter
41+
42+
snake = re.sub(r'([A-Z])', r'_\1', s)
43+
"""
44+
r'([A-Z])' -> raw string regex, matches uppercase letters.
45+
r'_\' -> replacement string
46+
=> \1 means "the text matched by the first capture group".(i think there in caes of multiple capture groups like () () () when use 1 the first capture group is insert remember this just only for my sake.
47+
=> So it inserts _ before the uppercase letter.
48+
"""
49+
return snake.lower()
50+
51+
if __name__ == "__main__":
52+
print(to_snake("myGuinnessRecord"))
53+
unittest.main()

0 commit comments

Comments
 (0)