This was the first problem and it took me a few hours to figure out an answer. The task to is implement a program that prompts the user for the name of a variable in camel case and outputs the corresponding name in snake case. It took me less than 3 minutes to come up with this, which satisfied any input where only one capital existed:
camelcase = input("camelCase: ")
for letter in camelcase:
if letter.isupper():
first, second, last = camelcase.partition(letter)
second = "_" + second.lower()
print("snakecase: ", first + second + last)
However to come up with the following to satisfy inputs with multiple capitals I spent a solid 2-3 hours:
camelcase = input("camelCase: ")
for letter in camelcase:
if letter.isupper():
_ = camelcase.split(letter)
_.insert(1, "_" + letter.lower())
camelcase = "".join(_)
print("snake_case:", camelcase)
I feel like given that this was the first problem, there is a simpler solution that I completely overlooked. Any advice? Please remember that my knowledge scope is only as far as lecture 3 which introduced loops.
I first tried adding a second if letter.isupper() loop to the final variable resulting from the .partition operation, however, that wasn't working as intended. Then I tried using the s.insert() method on the original input but learnt through the documentation that strings are immutable. Eventually after reading and experimenting with a plethora of different str functions and their results I managed to get to my submission.