tofu-api/tofu_api/common/string_utils.py

29 lines
991 B
Python

__all__ = [
'SNAKE_CASE_CHARACTERS',
'is_snake_case',
'str_to_snake_case',
]
import string
SNAKE_CASE_CHARACTERS = string.ascii_lowercase + string.digits + '_'
def is_snake_case(input_str: str) -> bool:
"""
Returns True if the input string only consists of snake case characters (lowercase letters, digits, underscore).
"""
return all(c in SNAKE_CASE_CHARACTERS for c in input_str)
def str_to_snake_case(input_str: str) -> str:
"""
Converts any string to a snake case string: Whitespaces are replaced with an underscore, uppercase letters are
converted to lowercase, and any non-alphanumeric character is removed.
"""
# First, lowercase string and replace any consecutive whitespaces with a single underscore
almost_snake_case = '_'.join(input_str.lower().split())
# Now, remove all characters that are neither letters, digits, nor underscores
return ''.join(filter(lambda c: c in SNAKE_CASE_CHARACTERS, almost_snake_case))