Python Practice › RegEx Programs › Program 15
camelCase to snake_case
Write a Python program to convert camelCase names to snake_case.
Output
firstName -> first_name getHTTPResponse -> get_httpresponse userIdNumber -> user_id_number
Approach
- Insert “_” before each capital, then lower-case.
Solution
import re for name in ["firstName", "getHTTPResponse", "userIdNumber"]: print(name, "->", re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower())Output
firstName -> first_name getHTTPResponse -> get_httpresponse userIdNumber -> user_id_number
Line by line
Line 4
The look-behind and look-ahead find the gap between a lowercase letter or digit and a capital, so “HTTP” stays together.
Learn the concept
New to this topic? Read the lesson, then come back.