This function converts the first word in a CamelCase work to lowercase. I.e. "CustomerID" becomes "customerID", "XMLInfo" becomes "xmlInfo"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import string
def lowerFirstCamelWord(word):
""" puts the first word in a CamelCase Word in lowercase.
I.e. CustomerID becomes customerID, XMLInfoTest becomes xmlInfoTest
"""
newstr = ''
swapped = word.swapcase()
idx = 0
# if it's all-caps, return an all-lowered version
lowered = word.lower()
if swapped == lowered:
return lowered
for c in swapped:
if c in string.lowercase:
newstr += c
idx += 1
else:
break
if idx < 2:
newstr += word[idx:]
else:
newstr = newstr[:-1]+ word[idx-1:]
return newstr
|
This function works by comparing flipping the case on all the characters in the CamelCase word, taking the first lowercase letters from that and, when the first capital letter shows up, take the rest of the letters from the original word.
If the word given is all in uppercase, an all-lowercased version is returned.
It can be expensive doing a character-by-character comparision of the word, but most of these words will be short (i.e. not thousands of characters long) so there shouldn't be a big performance impact.
a variant using re.
this site is good but its feedback is that it not show the full program code