I have the following code:
# tests/examples
cases = [
["getMyID", "get_my_id"],
["getMyAlphabetABC", "get_my_alphabet_abc"],
["getAlphabet", "get_alphabet"],
["simple", "simple"],
["getALetter", "get_a_letter"],
["getBook1", "get_book1"],
["simpleButNotSoSimpleBecauseItIsVeryLong", "simple_but_not_so_simple_because_it_is_very_long"]
]
def camel_case_to_underscore(t):
start = 0
parts = []
for idx, c in enumerate(t):
if c.isupper():
parts.append(t[start:idx].lower())
start = idx
parts.append(t[start:].lower())
for i in reversed([idx for idx, (i, j) in enumerate(zip(parts, parts[1:])) if len(i) == len(j) == 1]):
parts[i] = parts[i] + parts.pop(i + 1)
return "_".join(parts)
for p in cases:
print(camel_case_to_underscore(p[0]), camel_case_to_underscore(p[0]) == p[1]) # should be True for all
It seems quite clunky, but works. Is there a way that this can be optimised without using RegEx. I feel like it can be done in only one for
loop but I have had zero luck finding this method.
EDIT Small improvement (I think it's actually worse performer) but it feels closer to me.
def camel_case_to_underscore(t):
upper_idxs = [0] + [idx for idx, c in enumerate(t) if c.isupper()] + [len(t) + 1]
parts = [t[start:end].lower() for start, end in zip(upper_idxs[:-1], upper_idxs[1:])]
for i in reversed([idx for idx, (i, j) in enumerate(zip(parts, parts[1:])) if len(i) == len(j) == 1]):
parts[i] = parts[i] + parts.pop(i + 1)
return "_".join(parts)
'Dog'
? \$\endgroup\$["getALetter", "get_a_letter"]
?) \$\endgroup\$camel_case_to_snake('anSQLquery')
) \$\endgroup\$re
library? It's a standard part of Python (one of the "included batteries", if you like). \$\endgroup\$