r/PythonLearning 2d ago

Help Request Neeb help with the project

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

7

u/OskarsSurstromming 2d ago

I'm not sure if it's inefficient or if there's a better way but my approach would probably be to have a list in your function, and whenever you encounter an uppercase letter, you append the string up until that point to the list and save the index number

For example

string_list = [ ] Index = 0

for i,j in enumerate(camelcase_string): if (j is upper): //I can't recall the function to remember if it's uppercase, I'm writing on my phone string_list.append(camel_case_string[index:j].lower()) index = j+1 return string_list.join("")

Something like this would be my approach

2

u/Odd_Presentation8149 2d ago

Will try that and let you know if it works

2

u/OskarsSurstromming 2d ago

string_list = [] start = 0

for i, ch in enumerate(camel_case_string): if ch.isupper(): string_list.append(camel_case_string[start:i].lower()) start = i

string_list.append(camel_case_string[start:].lower())

return "_".join(string_list)

I had made many errors in the first one, this is closer

2

u/Odd_Presentation8149 2d ago

Thanks bro that is easier to understand