Search code examples
stringpython-2.7camelcasing

Python 2.7 - remove special characters from a string and camelCasing it


Input:

to-camel-case
to_camel_case

Desired output:

toCamelCase

My code:

def to_camel_case(text):
    lst =['_', '-']
    if text is None:
        return ''
    else:
        for char in text:
            if text in lst:
                text = text.replace(char, '').title()
                return text

Issues: 1) The input could be an empty string - the above code does not return '' but None; 2) I am not sure that the title()method could help me obtaining the desired output(only the first letter of each word before the '-' or the '_' in caps except for the first.

I prefer not to use regex if possible.


Solution

  • A better way to do this would be using a list comprehension. The problem with a for loop is that when you remove characters from text, the loop changes (since you're supposed to iterate over every item originally in the loop). It's also hard to capitalize the next letter after replacing a _ or - because you don't have any context about what came before or after.

    def to_camel_case(text):
        # Split also removes the characters
        # Start by converting - to _, then splitting on _
        l = text.replace('-','_').split('_')
    
        # No text left after splitting
        if not len(l):
            return ""
    
        # Break the list into two parts
        first = l[0]
        rest = l[1:]
    
        return first + ''.join(word.capitalize() for word in rest)
    

    And our result:

    print to_camel_case("hello-world")
    

    Gives helloWorld

    This method is quite flexible, and can even handle cases like "hello_world-how_are--you--", which could be difficult using regex if you're new to it.