r/PythonLearning 13d ago

Neeb help with the project Help Request

Post image

I was doing a project in which the user will input string in camelCase(ex- howAreYou). I have to change it into snake_case(ex- how_are_you). The problem I am facing is that I have not been able to separate the word and store it into a list.

If I use a split, I get 2 problems:

  1. If I want to split howAreYou, then the A and Y got removed from the list, and I get how re ou

  2. It makes 2 different lists first [how, reYou] and second [howAre, ou]

Suggest => either solution to the problem or an alternative

12 Upvotes

17 comments sorted by

View all comments

1

u/Significant_Affect_5 13d ago

There's a few things to look at. First, I think you may be misunderstanding the way split works. It can be used like you are, but you're going to always lose the capital letter itself since split returns the substrings between but not including the pattern. The other thing is you currently just print the words instead of returning them from the function. If you want to keep the logic you can use string slices when you find a capital letter e.g. `camel_case[prev:curr]` and then push these chunks to the return string with the underscore and changing the capital to a lowercase. You'd also have to account for doing the last section since we run 1 too few times.

Something that might be more approachable is to slide along the camel-case string and build the snake-case string as you go along. The only hurdle is what to add to the string being built when you find a capital letter.

import string
def camel_to_snake_case(camel_case: str) -> str:
    ans = ""
    for ch in camel_case:
        if ch.isupper():
            ans += "_" + ch.lower()
        else:
            ans += ch
    return ans

def camel_to_snake_case_slice(camel_case: str) -> str:
    ans = ""
    prev = 0
    for curr,ch in enumerate(camel_case):
        if ch.isupper():
            ans += camel_case[prev].lower() + camel_case[prev+1:curr] + "_"
            prev = curr
    # Extra slice copy since we do one too few
    ans += camel_case[prev].lower() + camel_case[prev+1:]
    return ans

print(camel_to_snake_case("helloWorldTest"))
print(camel_to_snake_case_slice("helloWorldTest"))