Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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:]))   
share|improve this question
    
Since this is under the code review section, I'll provide the answer I would in a real code review. Don't do it at all. Doing a refactoring of naming in this way has a fair chance of introducing bugs with no improvement in functionality. AKA: If it ain't broke don't fix it. Spend the time you save working on new features or fixing real problems. –  user69264 15 hours ago

3 Answers 3

up vote 11 down vote accepted

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.

share|improve this answer
    
I like the way you are doing the extraction. nice. –  JaDogg yesterday
    
Thanks very very much! –  Mark Soul yesterday
    
first, *rest = column.split('_') doesn't work in Python 2.x. –  Nizam Mohamed yesterday
    
@NizamMohamed you can use first, rest = column.split('')[0], column.spilt('')[1:] in Python 2.x –  Mark Soul yesterday
    
@ Mark Soul Thanks. Good idea. –  Nizam Mohamed yesterday

Using regex,

import re
def getJavaName(column):
    return re.sub('_.',lambda x: x.group()[1].upper(),column)
share|improve this answer

Consider writing this as a one-liner regular expression substitution instead.

import re

def get_java_name(column_name):
    return re.sub('_([a-z])', lambda match: match.group(1).upper(), column_name)

Since the function is Python code, it should still adhere to PEP 8 naming conventions — get_java_name() instead of getJavaName().

share|improve this answer
    
This fails for non-ASCII identifiers. You might argue that it's bad practice anyway, though ;). –  Veedrac yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.