I have written two functions, one actual and one helper, to convert camelCase strings into snake_case strings (I call it joint-lower case). Any ideas for improvement are welcome.
def _cc2jl(string):
"""Camel case to joint-lower helper."""
for index, current in enumerate(string):
if is_upper(current):
if index > 0:
previous = string[index-1]
if is_upper(previous):
try:
next = string[index+1]
except IndexError:
yield current.lower()
continue
else:
if is_upper(next):
yield current.lower()
continue
yield '_' + current.lower()
continue
yield current.lower()
continue
yield current
def cc2jl(string):
"""Converts a camel case string to joint-lower."""
return ''.join(_cc2jl(string))
Expected behaviour:
>>> cc2jl('m')
'm'
>>> cc2jl('AA')
'aa'
>>> cc2jl('MySQLDatabase')
'my_sql_database'
>>> cc2jl('GarbageCollection')
'garbage_collection'
>>> cc2jl('AAAAAAAAAAAAAAAAA')
'aaaaaaaaaaaaaaaaa'