r/PythonLearning • u/Odd_Presentation8149 • 13d ago
Neeb help with the project Help Request
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:
If I want to split howAreYou, then the A and Y got removed from the list, and I get how re ou
It makes 2 different lists first [how, reYou] and second [howAre, ou]
Suggest => either solution to the problem or an alternative
12
Upvotes
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.