trying to make snakecase program
Question:
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.
Answers:
Your function would work if snakecase
was empty, but it is not.
You should initialize it to snakecase = str()
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)
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)
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.
Your function would work if snakecase
was empty, but it is not.
You should initialize it to snakecase = str()
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)
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)