How to change names to some friendly names in python?

Question:

I have few dummy function names and I want to transform them as follows:

sample case 1

input : getDataType
output: Data_Type

sample case 2

input: getDatasetID
output: Dataset_ID

My code is as below:

def apiNames(funcName):
 name = funcName.split("get")[1]

 print(''.join('_' + char if char.isupper() else char
          for char in name).lstrip('_'))

apiNames("getDataType")
apiNames("getDatasetID")

it works for case 1 but not for case 2

case 1 Output:

Data_Type

case 2 Output:

Dataset_I_D
Asked By: Sushant Shelke

||

Answers:

I think regex is a better route to solving this.

Consider:

def apiNames(funcName):
    name = funcName.split("get")[1]

    print('_'.join([found for found in re.findall(r'[A-Z]*[a-z]*', name)][:-1]))
Answered By: JNevill

Just for the fun of it, here’s a more robust camelCASEParser that takes care of all the "corner cases". A little bit of lookahead goes a long way.

>>> pattern = '^[a-z]+|[A-Z][a-z]+|[A-Z]+(?![a-z])'
>>> "_".join(re.findall(pattern, "firstWordsUPPERCASECornerCasesEtc"))
'first_Words_UPPERCASE_Corner_Cases_Etc'

And yes, it also works if the pattern ends in an uppercase span. Negative lookahead succeeds at end of line.

>>> "_".join(re.findall(pattern, "andAShortPS"))
'and_A_Short_PS'

I’m pretty sure it works for any sequence matching ^[a-zA-Z]+. Try it.

Answered By: alexis
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.