0

The following code converts the camelcase to snake case:

 def convertToSnakeCase(name):
        s1 = re.sub('(.^_)([A-Z][a-z]+)', r'\1_\2', name)
        return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()

How would I go about converting, where I have 3 consecutive capital letters like ISM but split it like is_my:

ThisISMyTest --------------> This_is_my_test

Kush Patel
  • 11
  • 1
  • 4

2 Answers2

1

There may be a simpler way, but the following worked for me for converting camel to snake case without breaking up acronyms.

# Ex. LOLThisIsATest -> lol_this_is_a_test
def camel_to_snake_case(name: string):
    snake_case = name[0]
    for idx in range(1, len(name)-1):
        is_upper = name[idx].isupper()
        followed_by_lower = not name[idx+1].isupper()
        preceded_by_lower = not name[idx-1].isupper()
        if (is_upper and followed_by_lower) or (is_upper and preceded_by_lower):
            snake_case+='_'
        snake_case+=name[idx]
    snake_case+=name[len(name)-1] # append last letter
    return snake_case.lower()

# testing
print("Expected: lol_this_is_a_test")
print("Actual:   " + camel_to_snake_case("LOLThisIsATest"))
swess
  • 11
  • 3
-1

A little bit of a different approach, and works for the most part. I don't see how you can get around IS in ThisISMyTest since a program really couldn't tell what's a word without getting into natural language processing.

def convertToSnakeCase(name):
  split_name = list(name)
  for c in range(len(split_name)):
    if split_name[c].isupper() and c != 0 and split_name[c-1] != '_':
        split_name.insert(c,'_')
        c +=1

  return ''.join(split_name).lower()

print(convertToSnakeCase("ThisISMyTest"))

this_i_s_my_test

TheDetective
  • 642
  • 1
  • 6
  • 17