0

I'm trying to convert a string containing numbers from camel case to sanck case. Since the numbers must be separated with a snack case from the letters.

last20Days

last200Days

Result should be like:

last_20_days

last_200_days

I have tryed this:

def format_string_case(string):
    res = ""
    for index, char in enumerate(string):
        if char.isupper():
            res += "_" + char.lower()
        if char.isnumeric() and string[index + 1].isnumeric():
            res += "_" + f"{char}{string[index+1]}"
        elif char.islower() and not char.isnumeric():
            res += char
    return res[0:]

But is not working well:

last20Days return last_20_days But last200Days return last_20_00_days ( i want it to be like last_200_days)

  • [Elegant Python function to convert CamelCase to snake_case?](https://stackoverflow.com/a/46493824/6045800) – Tomerikoo Mar 16 '23 at 07:32

1 Answers1

0

This can be done more easily with a regex substitution:

import re

def format_string_case(string):
    return re.sub(
        r'(?<=[a-z0-9])[A-Z]+|(?<=[A-Za-z])[0-9]',
        lambda m: f'_{m[0].lower()}',
        string
    )

print(format_string_case('last20Days'))
print(format_string_case('last200Days'))

This outputs:

last_20_days
last_200_days

Demo: https://replit.com/@blhsing/HotpinkPricklyMachinelanguage

blhsing
  • 91,368
  • 6
  • 71
  • 106