Home > Back-end >  iterate with a conditional within a loop in python
iterate with a conditional within a loop in python

Time:09-20

I am learning Python and got stucked on one of the exercises. We have to convert camelCase into snake_case. I tried with a conditional in a loop:

camelCase = input("camelCase: ")
for c in camelCase:
    if c.islower():
        return c
    elif c.isupper():
        return ("_"   c.lower())

print("snake_case:"   c)

But I realized I didn´t understand how return works.

Now I tried making a list:

camelCase = input("camelCase: ")
snake_case = []
for c in camelCase:
    if c.islower():
        snake_case.append(c)
    elif c.isupper():
        snake_case.append("_"   c.lower())

print("snake_case:", snake_case)

But I don´t know how to get it like a string (word), it comes out like that.

camelCase: firstName
snake_case: ['f', 'i', 'r', 's', 't', '_n', 'a', 'm', 'e']

CodePudding user response:

Your current solution is creating a list and appending a string for each letter. If you want to have a string result, simple create an empty string and concatenate a string for each letter to that variable. Your solution may look something like:

camelCase = input("camelCase: ")
snake_case = ""
for c in camelCase:
    if c.islower():
        # 'x  = 1' is the same as 'x = x   1'
        snake_case  = c
    elif c.isupper():
        snake_case  = "_"   c.lower()

print("snake_case:", snake_case)

CodePudding user response:

In python you can just use strings rather than an explicit character array, and append to them with a =.

camelCase = input("camelCase: ")
snake_case = ""
for c in camelCase:
    if c.islower():
        snake_case  = c
    elif c.isupper():
        snake_case  = "_"   c.lower()
print("snake_case:", snake_case)

This gives you what you want:

camelCase: firstName
snake_case: first_name

CodePudding user response:

You've done the hard part, now all you need to do is get it into a string.

str.join is meant for that: you can just use:

print("snake_case:", ''.join(snake_case))

to join the elements in your list.

From the documentation of str.join:

str.join(iterable)

Return a string which is the concatenation of the strings in iterable. [...] The separator between elements is the string providing this method.


Note: you asked about return. That is only for functions (see below). If it is used outside of a function, an error will be raised.

Here is an example use of return:

def add_one(num):
    return num   1

print(add_one(5)) # Outputs 6

You might want to check this out to learn more about functions.

  • Related