Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Annotated Answers for Clarity solution in Clear category for Conversion into CamelCase by BootzenKatzen
# This is my solution without using hints:
def to_camel_case(name: str) -> str:
newstring = "" # Establishing an empty string to add to
index = 0 # Creating an index so we can iterate through the string
while index < len(name): # While our index is less than the length of the string - we loop
if index == 0: # If it's the first letter of the string
newstring += name[index].upper() # Add the uppercase version of the letter to our new string
index +=1 # Then advance the index
if name[index] == "_": # If the character from the string is an underscore
newstring += name[index + 1].upper() # Add the uppercase of the NEXT letter to the new string
index +=2 # Advance the index by 2 to move past the _ and the letter we added
else: # else - if it is NOT an underscore or the first letter
newstring += name[index] # just add that letter to the string
index += 1 # and advance the index
return newstring # When our loop is done, return the new string we created!
# This is their solution in the hints (which I admit is much sleeker):
def to_camel_case2(name: str) -> str:
return ''.join(i.capitalize() for i in name.split('_'))
# Let's break this down starting from the right (because that's how it makes sense to me)
# name.split('_') will break our string into a list of words based on the position of the "_"
# basically when it sees an underscore, it stops, and takes everything before it as a word,
# then moves to the next segment, until either the next underscore or the end of the string
# capitalize() returns a string with the first letter capitalized and the rest lowercase
# and the i.capitalize() for statement lets us iterate this function through the list of split words we created
# then once we have a list of capitalized words we use ''.join to smash them all back together
# without any spaces or characters between
# and return feeds that output back out into the program to where to_camel_case() is called
# just calling the function doesn't do anything really, but you could feed the result into a value
# or even into another function, or into something like the asserts below used to test your code
print("Example:")
print(to_camel_case("my_function_name"))
# These "asserts" are used for self-checking
assert to_camel_case("my_function_name") == "MyFunctionName"
assert to_camel_case("i_phone") == "IPhone"
print("The mission is done! Click 'Check Solution' to earn rewards!")
May 3, 2023
Comments: