Question

I'm trying to obtain verbose names from CamelCase strings in Python but have no idea how to approach the problem.

This is the usecase:

class MyClass(object):
    def verbose_name(self, camelcase):
        return "my class"
        # ^-- here I need a way to calculate the
        #     value using the camelcase argument

    def __str__(self):
        return self.verbose_name(self.__class__.__name__)

I tried to implement a solution where the chunks my and class are generated detecting transitions from lower to uppercase letters, but it's very procedural, doesn't work and it's becoming too complex for such a simple task.

Any suggestion for a simple implementation to solve the problem?

Was it helpful?

Solution

If I understand your requirement correctly, you want to split a camel case string on the Case boundary. Regex can be quite handy here

Try the following implementation

>>> ' '.join(re.findall("([A-Z][^A-Z]*)","MyClass")).strip()
'My Class'

The above implementation would fail if the name is non CamelCase conforming. In such cases, make the caps optional

>>> test_case = ["MyClass","My","myclass","my_class","My_Class","myClass"]
>>> [' '.join(re.findall("([A-Z]?[^A-Z]*)",e)) for e in test_case]
['My Class ', 'My ', 'myclass ', 'my_class ', 'My_ Class ', 'my Class ']

OTHER TIPS

Building on Abhijit's answer

def verbose_name(self, camelcase):
    return '_'.join(re.findall("([A-Z][^A-Z]*)", camelcase)).lower()

How about this:

def verbose_name(self, camelcase)
    return re.sub(r'([a-z])([A-Z])',r'\1 \2', camelcase).lower()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top