PYTHON
Convert camelCase to snake_case
Transform camelCase strings into snake_case using Python regex, perfect for standardizing variable names or API responses for consistency.
import re
def camel_to_snake(name):
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()
# Examples
print(camel_to_snake("camelCaseString")) # camel_case_string
print(camel_to_snake("anotherExampleName")) # another_example_name
print(camel_to_snake("HTTPResponseCode")) # http_response_code
print(camel_to_snake("firstName")) # first_name
How it works: This Python function `camel_to_snake` converts a string from camelCase to snake_case. It uses two regex substitutions: the first adds an underscore before any uppercase letter that is followed by one or more lowercase letters, and the second adds an underscore before any uppercase letter that is preceded by a lowercase letter or digit. Finally, the entire string is converted to lowercase to complete the snake_case format.