As part of a universal string-to-snake_case conversion, this regex-based approach is probably the best option:
import re
def to_snake_case(s: str) -> str:
s = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).replace('-', '_').lower()🧐 How does it work?
1️⃣
re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s) replaces each uppercase letter followed by lowercase letters with the same letter preceded by an underscore.2️⃣
re.sub('([a-z0-9])([A-Z])', r'\1_\2', s) replaces each uppercase letter preceded by a lowercase letter or digit with the same letter preceded by an underscore.3️⃣ Then everything is converted to lowercase and hyphens are replaced with underscores.
But let's step beyond the algorithmic task and see how to solve such a problem in real life. If the project uses Pydantic, then all this has long been written, tested on millions of lines of code, and is right out of the box:
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel, to_snake
class FrontendData(BaseModel):
model_config = ConfigDict(
alias_generator=to_camel, # Automatically expects camelCase on input
populate_by_name=True
)
python_talk: str # In code, we work with orthodox snake_caseUnder the hood, there are polished algorithms that account for edge cases, non-standard separators, and the wild imaginations of developers of adjacent systems.
And if Pydantic is not in the project, there are micro-libraries like inflection that do the same thing:
import inflection
inflection.underscore("CamelCaseAnd-kebab-case")
# -> 'camel_case_and_kebab_case'
inflection.camelize("python_talk", uppercase_first_letter=False)
# -> 'pythonTalk'Knowing regex algorithms is useful for passing algorithmic interviews and understanding how strings are parsed. But knowing the tools is necessary to avoid bringing self-written bicycles into production that will inevitably break on the first crooked payload.
#algosobes
Comments
0No comments yet.