Back
+30 XP
Concept

CamelCase to snake_case Bidirectional Converter

API gateways bridging Python backends (`snake_case`) and TypeScript clients (`camelCase`) require deterministic case converters. Going to `snake_case` inserts underscores at lowercase-to-uppercase transitions, while reversing splits on underscores and capitalizes non-initial tokens 🐍🐪🔀.

python
import re

def to_snake(name):
    s1 = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name)
    return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s1).lower()

def to_camel(name):
    parts = name.split("_")
    return parts[0] + "".join(w.capitalize() for w in parts[1:])

print("Snake:", to_snake("userSessionToken"))
print("Camel:", to_camel("user_session_token"))

# 7. CamelCase to snake_case Bidirectional Converter Full-stack applications constantly pass data across boundary lines: Python PEP 8 mandates `snake_case` (`user_profile_id`), while JavaScript and JSON API conventions overwhelmingly prefer `camelCase` (`userProfileId`) 🛑. ```python # The Case Mapping Challenge: # Python Backend: {"created_at": 1700000000, "is_verified": True} # TypeScript UI: {"createdAt": 1700000000, "isVerified": true} ``` ### The Acronym Trap in Regex A naive regex like `re.sub(r'([A-Z])', r'_\1', s).lower()` breaks on acronyms: - Input: `getHTTPStatus` - Naive Output: `get_h_t_t_p_status` (Terrible!) - Correct Output: `get_http_status` To solve this, use a two-pass regex: 1. `(.)([A-Z][a-z]+)` -> Separates the acronym prefix from the succeeding word (`HTTP` from `Response`). 2. `([a-z0-9])([A-Z])` -> Separates standard lowercase tokens from uppercase letters 🐍🐪🔀. --- ### Interactive Pop-Quiz 🧠 #### Why does simple `re.sub(r'([A-Z])', r'_\1', name)` fail on strings with consecutive acronyms like `parseHTTPResponse`? - [ ] It inserts an underscore before every single capital letter, yielding `parse_H_T_T_P_Response` instead of `parse_http_response` 🛑 - [ ] Because uppercase letters crash the regex engine - [ ] Acronyms require UTF-16 encoding to convert - [ ] Because Python forbids more than two capital letters in identifiers --- ### Practical Challenge 🎯 Implement `camel_to_snake(s: str) -> str` and `snake_to_camel(s: str) -> str`. Handle standard camelCase and acronym transitions (`'parseHTTPResponse'` -> `'parse_http_response'`). Verify `'userAuthToken'` converts to `'user_auth_token'` and back, assert equality, and print results. <details> <summary>Solution</summary> ```python import re def camel_to_snake(s: str) -> str: s1 = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", s) return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s1).lower() def snake_to_camel(s: str) -> str: parts = s.split("_") return parts[0] + "".join(word.capitalize() for word in parts[1:]) camel = "userAuthToken" snake = camel_to_snake(camel) restored = snake_to_camel(snake) assert snake == "user_auth_token" assert restored == camel assert camel_to_snake("parseHTTPResponse") == "parse_http_response" print(f"Bidirectional conversion verified: '{camel}' <-> '{snake}'") ``` </details>

Checkpoint

Why does simple `re.sub(r'([A-Z])', r'_\1', name)` fail on strings with consecutive acronyms like `parseHTTPResponse`? 🧠

Practice

Implement `camel_to_snake(s: str) -> str` and `snake_to_camel(s: str) -> str`. Handle standard camelCase and acronym transitions (`'parseHTTPResponse'` -> `'parse_http_response'`). Verify `'userAuthToken'` converts to `'user_auth_token'` and back, assert equality, and print results. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks