简体   繁体   中英

Convert not_camel_case to notCamelCase and/or NotCamelCase in Python?

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
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:]

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)

@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:])

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

str.title().replace("_", "")

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM