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
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.