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

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).


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("_"))

Tags:

Python