Files
30-seconds-of-code/snippets/snake.md
Riadh Fezzani 76ead08704 Update snippets/snake.md
Co-Authored-By: Angelos Chalaris <chalarangelo@gmail.com>
2019-10-01 14:46:42 +02:00

589 B

title, tags
title tags
snake string,regexp,intermediate

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(str):
    return '_'.join(re.sub('([A-Z][a-z]+)', r' \1',
                    re.sub('([A-Z]+)', r' \1', str)).split()).lower()
snake('camelCase') # 'camel_case'
snake('some text') # 'some_text'
snake('some-mixed_string With spaces_underscores-and-hyphens') # 'some_mixed_string_with_spaces_underscores_and_hyphens'
snake('AllThe-small Things') # "all_the_smal_things"