I have written the function below that converts underscore to camelcase with first word in lowercase, i.e. "get_this_value" -> "getThisValue". Also I have requirement to preserve leading and trailing underscores and also double (triple etc.) underscores, if any, i.e.
"_get__this_value_" -> "_get_ThisValue_".
output = ""
first_word_passed = False
for word in value.split("_"):
if not word:
output += "_"
output += word.capitalize()
output += word.lower()
first_word_passed = True
Your code is fine. The problem I think you're trying to solve is that
if first_word_passed looks a little bit ugly.
One option for fixing this is a generator. We can easily make this return one thing for first entry and another for all subsequent entries. As Python has first-class functions we can get the generator to return the function we want to use to process each word.
We then just need to use the conditional operator so we can handle the blank entries returned by double underscores within a list comprehension.
So if we have a word we call the generator to get the function to use to set the case, and if we don't we just use
_ leaving the generator untouched.
def underscore_to_camelcase(value): def camelcase(): yield str.lower while True: yield str.capitalize c = camelcase() return "".join(c.next()(x) if x else '_' for x in value.split("_"))