Python Practice › RegEx Programs › Program 15

camelCase to snake_case

EasyRegEx Programs · 15 of 20

Write a Python program to convert camelCase names to snake_case.

Advertisement
Output
firstName -> first_name
getHTTPResponse -> get_httpresponse
userIdNumber -> user_id_number

Approach

  1. Insert “_” before each capital, then lower-case.

Solution

Python
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.

More regex programs

← All 20 RegEx Programs

Leave a Comment