Search code examples
listpython-3.xcamelcasing

How to split CamelCase into a list (python)


I have been trying for a month and can't get anywhere with this. I have an exam very soon but I can't figure this out. I need a way to split a CamelCase statement into a list in python, and the list should have room for 10 words. If less than 10 words are in the statement then the empty spots on the list should say (Empty).

[edit] the input would be something like ThisIsCamelCase and the expected output would be an array the contents of which are This Is Camel Case (Empty) (Empty)

so far I've been able to put this together:

def un_camel(input): output = [input[0].lower()] for c in input[1:]: if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'): output.append(' ') output.append(c.lower()) else: output.append(c) return str.join('', output) It can split camel case but not accomplish the array part


Solution

  • Using a regular expression would do most of the job:

    In [10]: import re
    
    In [11]: re.sub('([a-z])([A-Z])', r'\1 \2', 'ThisIsCamelCase').split()
    Out[11]: ['This', 'Is', 'Camel', 'Case']
    

    Make the list 10 items long:

    In [23]: a = re.sub('([a-z])([A-Z])', r'\1 \2', 'ThisIsCamelCase').split()
    
    In [24]: a + [None]*(10 - len(a))
    Out[24]: ['This', 'Is', 'Camel', 'Case', None,
               None, None, None, None, None]
    

    (This seems like an unPythonic thing to do, by the way).

    If you must use (Empty) instead of a sensible value like None:

    In [26]: a + ['(Empty)']*(10 - len(a))
    Out[26]: 
    ['This', 'Is', 'Camel', 'Case', '(Empty)',
     '(Empty)', '(Empty)', '(Empty)', '(Empty)', '(Empty)']