Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
list comprehension or basic for loop; which is better? solution in Clear category for Conversion from CamelCase by lucas.stonedrake
# a solution using list comprehension
def from_camel_case(name):
# make a list with underscores in front of capitals
lst = [x if x.islower() else '_' + x for x in name]
#join the list, make it all lower case, and remove the first underscore
return ''.join(lst).lower().lstrip('_')
# a solution without list comprehension
def from_camel_case(name):
lst = [] # make an empty list
for char in name: # for every letter in name
if char.isupper(): lst += '_' + char #add underscores in front of capitals
else: lst += char
#join the list, make it all lower case, and remove the first underscore
return ''.join(lst).lower().lstrip('_')
if __name__ == '__main__':
print("Example:")
print(from_camel_case("Name"))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert from_camel_case("MyFunctionName") == "my_function_name"
assert from_camel_case("IPhone") == "i_phone"
assert from_camel_case("ThisFunctionIsEmpty") == "this_function_is_empty"
assert from_camel_case("Name") == "name"
print("Coding complete? Click 'Check' to earn cool rewards!")
Nov. 6, 2020
Comments: