Reputation: 21056
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?
Upvotes: 1
Views: 314
Reputation: 63737
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 ']
Upvotes: 4
Reputation: 3658
Building on Abhijit's answer
def verbose_name(self, camelcase):
return '_'.join(re.findall("([A-Z][^A-Z]*)", camelcase)).lower()
Upvotes: 2
Reputation: 438
How about this:
def verbose_name(self, camelcase)
return re.sub(r'([a-z])([A-Z])',r'\1 \2', camelcase).lower()
Upvotes: 0