Learn Python List Comprehension by Building a Case Converter Program - Step 20

Tell us what’s happening:

I am having trouble figuring out this code, I have tried everything: here it is: snake_cased_char_list = [
‘_’ + char.lower() if char.isupper() else char
for char in pascal_or_camel_cased_string
]

Your code so far

def convert_to_snake_case(pascal_or_camel_cased_string):
    # snake_cased_char_list = []
    # for char in pascal_or_camel_cased_string:
    #     if char.isupper():
    #       converted_character = '_' + char.lower()
    #       snake_cased_char_list.append(converted_character)
    #     else:
    #         snake_cased_char_list.append(char)
    # snake_cased_string = ''.join(snake_cased_char_list)
    # clean_snake_cased_string = snake_cased_string.strip('_')

    # return clean_snake_cased_string


# User Editable Region

    snake_cased_char_list = [
        '_' + char.lower() if char.isupper() else char
        for char in pascal_or_camel_cased_string
    ]
    

# User Editable Region

    return ''.join(snake_cased_char_list).strip('_')

def main():
    print(convert_to_snake_case('aLongAndComplexString'))

main()
1 Like

please share the link to the step, it looks like you removed it

this is PascalCase: NameOfFunction and this is camelCase: nameOfFunction, but snake_case is like this: name_of_function, so in order to obtain a snake_case, we need to have all words in lower case separated but "" in place of white space, so the whole function is about:
snake_cased_char_list = ['
’ + char.lower() if char.isupper() else char for char in pascal_or_camel_cased_string]
so we need to convert the upper letters to lower after an “_”, and this is the condition.
In general, a comprehensive list is made like the following:
[EXPRESSION1 if CONDITION else EXPRESSION2 for ITERATOR in ITERABLE] which is equivalent of:
for ITERATOR in ITERABLE: “for example, for i in range(10)”
if CONDITION:
lst.append(EXPRESSION1)
else:
lst.append(EXPRESSION2)

Welcome to the forum @Newaccount

Follow the example above to add an if clause to your list comprehension so that the expression is executed only if the character is uppercase.

Try adding the if statement to the end of the expression.

Happy coding

The step it is, is Step 20.

Thanks! I tried this and it didn’t work.

Is their anywhere I can look that can help me better? I tried this and couldn’t get it still.

Please share your updated code.

Is there any confusing point that you have a question about?