HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Transform snake_case to camelCase

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
transformsnake_casecamelcase

Problem

I want to convert db columns such as is_deleted or product_code which consist of xx_xx to java-style names: isDeleted or productCode. I wonder if there is a way to improve my following code, using regex or such things.

def getJavaName(column):                                                         
   words = column.split('_')                                                    
   first = words[0]                                                             
   return first + ''.join((w.capitalize() for w in words[1:]))

Solution

You should remove the many trailing spaces.

You can replace slicing with unpacking and the double-brackets can be removed:

def getJavaName(column):
   first, *rest = column.split('_')
   return first + ''.join(word.capitalize() for word in rest)


Python uses snake_case, even if your DB columns don't, so you should be calling this get_java_name - although personally it's still better named snake_to_camel_case and the column parameter should be renamed to, say, name.

Code Snippets

def getJavaName(column):
   first, *rest = column.split('_')
   return first + ''.join(word.capitalize() for word in rest)

Context

StackExchange Code Review Q#85311, answer score: 12

Revisions (0)

No revisions yet.