Next / Previous / Contents / Shipman's homepage

40. deCamel(): Convert from camel-case to dashed attribute names

fosox.py
# - - -   d e C a m e l

def deCamel(name):
    '''Change camelCase names to hyphenated-names.

      [ name is a str ->
          return name, transformed by substituting "x-y"
          for any sequence "xY" where x is lowercase and Y is
          uppercase ]
    '''
    #-- 1
    last = 'A'
    result = []

    #-- 2
    # [ result  +:=  all but the first character of (last+name)
    #       with sequences "xY" replaced replaced by "x-y" and
    #       "." replaced by "_"
    #   last  :=  the last character of name ]
    for c in name:
        #-- 2 body
        if last.islower() and c.isupper():
            result.append("-" + c.lower())
        elif c=='.':
            result.append('_')
        else:
            result.append(c)
        last = c

    #-- 3
    return ''.join(result)