1

Basically, the reverse of this. Here's my attempt, but it's not working.

def titlecase(value):
    s1 = re.sub('(_)([a-z][A-Z][0-9]+)', r'\2'.upper(), value)
    return s1
Community
  • 1
  • 1
john2x
  • 22,546
  • 16
  • 57
  • 95

5 Answers5

9
def titlecase(value):
    return "".join(word.title() for word in value.split("_"))

Python is more readable than regex, and easier to fix when it's not doing what you want.

If you want the first letter lowercase as well, I would use a second function that calls the function above to do most of the work, then just lowercases the first letter:

def titlecase2(value):
     return value[:1].lower() + titlecase(value)[1:]
kindall
  • 178,883
  • 35
  • 278
  • 309
  • 1
    Precisely. The regexes were a red herring. Never use a regex for anything before checking whether the methods of a string object will do what you want. In this case, `split` tokenizes the string and `title` conveniently capitalizes a word. – Michael Dillon Aug 14 '11 at 23:30
2

You have an error with your regex. Instead of

([a-z][A-Z][0-9]+) # would match 'oN3' but not 'one'

use

([a-zA-Z0-9]+) # matches any alphanumeric word

However, this also won't work because r'\2'.upper() can't be used that way. Instead, try:

s1 = re.sub('(_)([a-zA-Z0-9]+)', lambda p: p.group(2).capitalize(), value)
jtbandes
  • 115,675
  • 35
  • 233
  • 266
2

@kindall provide good solution(credit goes to him). But if you want syntax "myCamel" the first word does not need to be capitalized then you have to change a bit:

def titlecase(value):
     rest = value.split("_")
     return rest[0]+"".join(word.title() for word in rest[1:])
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
2

For NotCamelCase, Using a regex or a loop sounds like an overkill.

str.title().replace("_", "")
Bharad
  • 529
  • 1
  • 6
  • 15
0

Like jtbandes said, you should mash the character classes together like

([a-zA-Z0-9]+)

The next trick is what you do with the replacement. When you say

r'\2'.upper()

the upper() actually happens before called sub. But you can use another feature of sub: you can pass a function to handle the match:

re.sub('(_)([a-zA-Z0-9]+)', lambda match: match.group(2).capitalize(), value)

Now your lambda will get called with the match. Also you can use subn to have the replacement happen on more than one place:

re.subn('(_)([a-zA-Z0-9]+)', lambda match: match.group(2).capitalize(), value)[0]
Owen
  • 38,836
  • 14
  • 95
  • 125