Convert Text to snake_case
Learn how to convert text to snake_case for Python, Ruby, and database column naming. Understand snake_case conventions, word separation with underscores, and when to prefer it over other cases.
Detailed Explanation
Converting Text to snake_case
snake_case replaces all spaces and delimiters with underscores (_) and lowercases every letter. It is called "snake case" because the underscores resemble a snake lying on the ground between the words.
Basic Conversion
Input: User First Name
Output: user_first_name
Input: backgroundColor
Output: background_color
Input: GET-API-RESPONSE
Output: get_api_response
Where snake_case Is Used
snake_case is the dominant convention in several ecosystems:
# Python — variables, functions, methods, modules (PEP 8)
user_name = "Alice"
def get_user_profile(user_id):
pass
import json_parser
# Ruby — variables, methods, file names
first_name = "Alice"
def calculate_total_price(items)
end
Database Column Naming
snake_case is the de facto standard for database schemas:
CREATE TABLE user_profiles (
user_id SERIAL PRIMARY KEY,
first_name VARCHAR(100),
last_name VARCHAR(100),
email_address VARCHAR(255),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP
);
PostgreSQL, MySQL, and SQLite all conventionally use snake_case for table and column names.
API Design
REST APIs often use snake_case for JSON keys, especially in Ruby on Rails and Python ecosystems:
{
"user_id": 42,
"first_name": "Alice",
"created_at": "2025-01-15T10:30:00Z"
}
Conversion Algorithm
- Insert an underscore before each uppercase letter that follows a lowercase letter (for camelCase input).
- Replace all hyphens, dots, and spaces with underscores.
- Collapse consecutive underscores into one.
- Lowercase the entire string.
- Trim leading and trailing underscores.
Handling Acronyms
"XMLParser" → "xml_parser"
"getHTTPSUrl" → "get_https_url"
"userID" → "user_id"
Acronyms are split at the boundary where an uppercase run meets a lowercase character.
Edge Cases
- Single word:
"hello"→"hello". - Already snake_case: passes through unchanged.
- Consecutive uppercase:
"HTMLParser"→"html_parser". - Numbers:
"item2Count"→"item_2_count"or"item2_count"depending on the algorithm.
Use Case
snake_case is required by Python (PEP 8) and Ruby style guides for variable and function names. It is the standard for database column names across all major RDBMS systems, Rust variable names, and is commonly used for REST API JSON keys in Python and Ruby backends. Converting from camelCase or PascalCase to snake_case is a frequent task when mapping between JavaScript frontends and Python/Ruby backends.