30 seconds of python

  Back to Home

snake

stringregexpintermediate

Converts a string to snake case.

Break the string into words and combine them adding _ as a separator, using a regexp.

import re

def snake(s):
  return '_'.join(re.sub('([A-Z][a-z]+)', r' \1',
    re.sub('([A-Z]+)', r' \1',
    s.replace('-', ' '))).split()).lower()