Cc4c514481dbf2cf9f602188dee3c212

Hi, I'm a python newbie. Could someone look at this small snippet of code I made and give suggestions to working more Pythonic? I wouldn't know better if I'm writing ugly python code so please let me know if I am. Thanks!

def space_out_camel_case(stringAsCamelCase):
    """Adds spaces to a camel case string.  Failure to space out string returns the original string.
    >>> space_out_camel_case('DMLSServicesOtherBSTextLLC')
    'DMLS Services Other BS Text LLC'
    """
    retValue = ''
    
    if stringAsCamelCase is None:
        return None
    
    try:
        retValue = ''
        humpFinder = re.compile('([A-Z][a-z])|([a-z][A-Z][a-z])|([a-z][A-Z])') # DMLSServicesOtherBSTextLLC would match "Se", "sOt", "rB", "Te", "tL")
        humpMatches = humpFinder.finditer(stringAsCamelCase)
        
        # Determine each position in the original string that requires a space
        spaceIndicies = []
        for previousSpacesAdded,match in enumerate(humpMatches):
            spaceIndicies.append(match.start() + re.search('[A-Z]', match.group()).start() + previousSpacesAdded)
        
        # Split up the string, adding spaces where appropriate
        retValue = list(stringAsCamelCase)
        for spaceIndex in spaceIndicies: retValue.insert(spaceIndex, ' ')
        retValue = ''.join(retValue)
            
    except:
        print 'Encountered error adding spaces to %s' % stringAsCamelCase
        retValue = stringAsCamelCase
        
    return retValue

Refactorings

No refactoring yet !

81a73740df646bc6cccbfef6fab61ec9

Simon Hartley

December 27, 2008, December 27, 2008 12:53, permalink

1 rating. Login to rate!

I think you probably just missed the sub method.
I don't really have a good reason for using a lambda here over a function, apart from the fact that I think they're cool. I don't have a python interpreter available to test this unfortunately, but it can probably be fixed up fairly straight-forwardly.

def space_out_camel_case(stringAsCamelCase):
    """Adds spaces to a camel case string.  Failure to space out string returns the original string.
    >>> space_out_camel_case('DMLSServicesOtherBSTextLLC')
    'DMLS Services Other BS Text LLC'
    """
    
    if stringAsCamelCase is None:
        return None

    pattern = re.compile('([A-Z][A-Z][a-z])|([a-z][A-Z])')
    return pattern.sub(lambda m: m.group()[:1] + " " + m.group()[1:], stringAsCamelCase):
45b006ca8f5ea3e8c845e2cb6e1111d0

Guido Python

January 16, 2009, January 16, 2009 21:10, permalink

No rating. Login to rate!

Here's my 2 cents on this topic. You can get the libraries used in my code from http://www.pypi.info.

class DeCamelCaseMethods(Enum):
    default = 2**0
    force_lower_case = 2**1

def de_camel_case(stringAsCamelCase,delim=' ',method=DeCamelCaseMethods.default):
    """Adds spaces to a camel case string.  Failure to space out string returns the original string.
    >>> space_out_camel_case('DMLSServicesOtherBSTextLLC')
    'DMLS Services Other BS Text LLC'
    """
    import re
    
    if stringAsCamelCase is None:
        return None

    normalize = lambda s:s
    if (method == DeCamelCaseMethods.force_lower_case):
	normalize = lambda s:s.lower()
    
    pattern = re.compile('([A-Z][A-Z][a-z])|([a-z][A-Z])')
    return normalize(pattern.sub(lambda m: m.group()[:1] + delim + m.group()[1:], stringAsCamelCase))
D41d8cd98f00b204e9800998ecf8427e

snies

May 11, 2009, May 11, 2009 12:55, permalink

No rating. Login to rate!

@ Simon Hartley: Wouldn't it be better to put the re.compile outside of the function definition? Otherwise it will be executed for each function call.

931ae7bf5fe3d90dc7016c7e8058e734

onk

March 7, 2010, March 07, 2010 19:38, permalink

No rating. Login to rate!

Positional regex.

def space_out_camel_case(s):
    """Adds spaces to a camel case string.  Failure to space out string returns the original string.
    >>> space_out_camel_case('DMLSServicesOtherBSTextLLC')
    'DMLS Services Other BS Text LLC'
    """

    return re.sub('((?=[A-Z][a-z])|(?<=[a-z])(?=[A-Z]))', ' ', s)

Your refactoring





Format Copy from initial code

or Cancel