omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / camel-case-and-snake-case / oracle.py
| 1 | # Independent reference for "Camel case and snake case" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | SEP = "_- " |
| 4 | def split_edges(s): |
| 5 | core = s.strip(" ") |
| 6 | if not core: |
| 7 | return s, "", "" |
| 8 | l = len(s) - len(s.lstrip(" ")) |
| 9 | t = len(s.rstrip(" ")) |
| 10 | return s[:l], s[l:t], s[t:] |
| 11 | def snake(s): |
| 12 | a, core, b = split_edges(s) |
| 13 | out = [] |
| 14 | for i, c in enumerate(core): |
| 15 | if c in SEP: |
| 16 | out.append("_") |
| 17 | elif "A" <= c <= "Z": |
| 18 | if i > 0 and core[i - 1] not in SEP: |
| 19 | out.append("_") |
| 20 | out.append(c.lower()) |
| 21 | else: |
| 22 | out.append(c) |
| 23 | return a + "".join(out) + b |
| 24 | def camel(s): |
| 25 | a, core, b = split_edges(s) |
| 26 | out, up = [], False |
| 27 | for c in core: |
| 28 | if c in SEP: |
| 29 | up = True |
| 30 | else: |
| 31 | out.append(c.upper() if up and "a" <= c <= "z" else c) |
| 32 | up = False |
| 33 | return a + "".join(out) + b |
| 34 | for s in ['snakeCase', 'snake_case', 'variable_10_case', 'variable10Case', 'hurry-up-joe!', 'c://my-docs/happy_Flag-Day/12.doc', ' spaces ']: |
| 35 | print(f"{s} -> snake: {snake(s)} -> camel: {camel(s)}") |