Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simplify this conversion from underscore to camelcase in Python?

Tags:

python

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_". 

The code:

def underscore_to_camelcase(value):     output = ""     first_word_passed = False     for word in value.split("_"):         if not word:             output += "_"             continue         if first_word_passed:             output += word.capitalize()         else:             output += word.lower()         first_word_passed = True     return output 

I am feeling the code above as written in non-Pythonic style, though it works as expected, so looking how to simplify the code and write it using list comprehensions etc.

like image 785
Serge Tarkovski Avatar asked Nov 29 '10 12:11

Serge Tarkovski


People also ask

How do you convert underscore to camelCase?

First, capitalize the first letter of the string. Run a loop till the string contains underscore (_). Replace the first occurrence of a letter that present after the underscore to the capitalized form of the next letter of the underscore. Print the modified string.


2 Answers

This one works except for leaving the first word as lowercase.

def convert(word):     return ''.join(x.capitalize() or '_' for x in word.split('_')) 

(I know this isn't exactly what you asked for, and this thread is quite old, but since it's quite prominent when searching for such conversions on Google I thought I'd add my solution in case it helps anyone else).

like image 146
Siegfried Gevatter Avatar answered Sep 19 '22 11:09

Siegfried Gevatter


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("_")) 
like image 42
Dave Webb Avatar answered Sep 20 '22 11:09

Dave Webb