Search code examples
pythonsnakecase

trying to make snakecase program


so i have to make an snakecase program

camelcase = input("camelCase: ")

snakecase = camelcase.lower()

for c in camelcase:
    if c.isupper():
        snakecase += "_"
        snakecase += c.lower()
        print(snakecase)

with the for im going through each letter, the if is for finding the uppercase right? but im failing on the last part, i dont really understand how to not add the "_" and c.lower() at the end of the word but just replace it.


Solution

  • With += you are adding the _ to the end of the snakecase variable. This you do for every uppercase character and then add the character itself. The output should be something like myteststring_t_s for myTestString.

    Instead, build the new string one char by the other.

    camel_case = 'myTestString'
    snake_case = ""
    
    for c in camel_case:
        if c.isupper():
            snake_case += f'_{c.lower()}'
        else:
            snake_case += c
    
    print(snake_case)