카멜 표기의 스트링을 스네이크 표기법으로 바꾸는 방법 없을까요
조회수 2511회
1 답변
-
1.inflection 라이브러리의 inflection.underscore사용
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))
출력 :
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
2. inflection을 쓸 수 없는 경우 - 사용자가 직접 정의
import re #re.sub를 위해 필요 def convert(name): #직접 정의한 함수 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))
출력 :
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
댓글 입력