카멜 표기의 스트링을 스네이크 표기법으로 바꾸는 방법 없을까요

조회수 2511회

"CamelCase" -> "camel_case" 같이 카멜 표기법으로 쓰인 스트링을 스네이크 표기법으로 바꾸려면 어떻게 해야 되나요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    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
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)