Skip to content
This repository was archived by the owner on May 7, 2023. It is now read-only.

Files

Latest commit

 

History

History
31 lines (26 loc) · 802 Bytes

snake.md

File metadata and controls

31 lines (26 loc) · 802 Bytes
title type tags cover dateModified
Snakecase string
snippet
string
regexp
organizer
2020-11-02 19:28:35 +0200

Converts a string to snake case.

  • Use re.sub() to match all words in the string, str.lower() to lowercase them.
  • Use re.sub() to replace any - characters with spaces.
  • Finally, use str.join() to combine all words using - as the separator.
from re import sub

def snake(s):
  return '_'.join(
    sub('([A-Z][a-z]+)', r' \1',
    sub('([A-Z]+)', r' \1',
    s.replace('-', ' '))).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_small_things'