"CamelCase" -> "camel_case" How can I change the string written in camel notation to snake notation?
python camelcasing
import inflection
str1 = 'CamelCase'
str2 = 'CamelCamelCase'
str3 = 'Camel2Camel2Case'
str4 = 'getHTTPResponseCode'
str5 = 'get2HTTPResponseCode'
str6 = 'HTTPResponseCode'
str7 = 'HTTPResponseCodeXYZ'
print(str1+" :\t\t\t\t"+inflection.underscore(str1))
print(str2+" :\t\t"+inflection.underscore(str2))
print(str3+" :\t\t"+inflection.underscore(str3))
print(str4+" :\t"+inflection.underscore(str4))
print(str5+" :\t"+inflection.underscore(str5))
print(str6+" :\t\t"+inflection.underscore(str6))
print(str7+" :\t"+inflection.underscore(str7))
Output:
CamelCase : camel_case
CamelCamelCase : camel_camel_case
Camel2Camel2Case : camel2_camel2_case
getHTTPResponseCode : get_http_response_code
get2HTTPResponseCode : get2_http_response_code
HTTPResponseCode : http_response_code
HTTPResponseCodeXYZ : http_response_code_xyz
required for import re #re.sub
def convert(name): #Directly defined function
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
str1 = 'CamelCase'
str2 = 'CamelCamelCase'
str3 = 'Camel2Camel2Case'
str4 = 'getHTTPResponseCode'
str5 = 'get2HTTPResponseCode'
str6 = 'HTTPResponseCode'
str7 = 'HTTPResponseCodeXYZ'
print(str1+" :\t\t\t\t"+convert(str1))
print(str2+" :\t\t"+convert(str2))
print(str3+" :\t\t"+convert(str3))
print(str4+" :\t"+convert(str4))
print(str5+" :\t"+convert(str5))
print(str6+" :\t\t"+convert(str6))
print(str7+" :\t"+convert(str7))
Output:
CamelCase : camel_case
CamelCamelCase : camel_camel_case
Camel2Camel2Case : camel2_camel2_case
getHTTPResponseCode : get_http_response_code
get2HTTPResponseCode : get2_http_response_code
HTTPResponseCode : http_response_code
HTTPResponseCodeXYZ : http_response_code_xyz
© 2024 OneMinuteCode. All rights reserved.