-1

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.

omen
  • 9
  • 2

2 Answers2

2

Use list comprehension: it is more Pythonic and concise:

camelcase = input("camelCase: ")
snakecase = ''.join(c if c.lower() == c else '_' + c.lower() for c in camelcase)
print(snakecase)
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
1

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)
Cpt.Hook
  • 590
  • 13