Join words with an underscore into lowercase and remove symbols. Parameters ----------- value: :class:`str` The value to convert. strict: :class:`bool` Whether or not to force single underscores. Returns -------- :class:`str` The value in sn
(value: str, strict: bool = True)
| 23 | |
| 24 | |
| 25 | def snake_case(value: str, strict: bool = True) -> str: |
| 26 | """ |
| 27 | Join words with an underscore into lowercase and remove symbols. |
| 28 | |
| 29 | Parameters |
| 30 | ----------- |
| 31 | value: :class:`str` |
| 32 | The value to convert. |
| 33 | strict: :class:`bool` |
| 34 | Whether or not to force single underscores. |
| 35 | |
| 36 | Returns |
| 37 | -------- |
| 38 | :class:`str` |
| 39 | The value in snake_case. |
| 40 | """ |
| 41 | |
| 42 | def substitute_word(symbols: str, word: str, is_start: bool) -> str: |
| 43 | if not word: |
| 44 | return "" |
| 45 | if strict: |
| 46 | delimiter_count = 0 if is_start else 1 # Single underscore if strict. |
| 47 | elif is_start: |
| 48 | delimiter_count = len(symbols) |
| 49 | elif word.isupper() or word.islower(): |
| 50 | delimiter_count = max( |
| 51 | 1, len(symbols) |
| 52 | ) # Preserve all delimiters if not strict. |
| 53 | else: |
| 54 | delimiter_count = len(symbols) + 1 # Extra underscore for leading capital. |
| 55 | |
| 56 | return ("_" * delimiter_count) + word.lower() |
| 57 | |
| 58 | snake = re.sub( |
| 59 | f"(^)?({SYMBOLS})({WORD_UPPER}|{WORD})", |
| 60 | lambda groups: substitute_word(groups[2], groups[3], groups[1] is not None), |
| 61 | value, |
| 62 | ) |
| 63 | return snake |
| 64 | |
| 65 | |
| 66 | def pascal_case(value: str, strict: bool = True) -> str: |