ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Converting Between Different Naming Convetions
Submitter: Sami Hangaslammi (other recipes)Sami Hangaslammi (other recipes)
Last Updated: 2001/07/09
Version no: 1.0
Category: Text

 

4 stars 2 vote(s)


Description:

These short functions convert identifier names between the most common naming conventions: CapitalizedWords, mixedCase and under_scores.

Source: Text Source

import re

def cw2us(x): # capwords to underscore notation
    return re.sub(r'(?<=[a-z])[A-Z]|(?<!^)[A-Z](?=[a-z])', r"_\g<0>", x).lower()

def mc2us(x): # mixed case to underscore notation
    return cw2us(x)

def us2mc(x): # underscore to mixed case notation
    return re.sub(r'_([a-z])', lambda m: (m.group(1).upper()), x)

def us2cw(x): # underscore to capwords notation
    s = us2mc(x)
    return s[0].upper()+s[1:]

##
## Expected output:
##
## >>> cw2us("PrintHTML")
## 'print_html'
## >>> cw2us("IOError")
## 'io_error'
## >>> cw2us("SetXYPosition")
## 'set_xy_position'
## >>> cw2us("GetX")
## 'get_x'
##

Discussion:



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Changing return value ...

5. Quantum Superposition

6. Pickle objects under ...

7. Generalized delegates ...

8. Reorder a sequence (uses ...

9. Setting Win32 System ...

10. ObjectMerger




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.