스트링에 단어 첫 글자를 대문자로 바꾸는 방법에 대해서 알고싶습니다

조회수 9082회

'the brown fox' -> 'The Brown Fox' 이런 식으로 스트링에 있는 모든 단어의 첫 글자를 대문자로 바꿔주고 싶습니다. 제일 쉬운 방법을 알려주세요

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    보통 앞글자만 대문자로 변환하는 경우는 다음의 3가지 메소드를 씁니다.

    1. 스트링의 첫 단어의 첫 글자만 대문자로 바꾸는 경우 - str.capitalize()

    mystr = "john, they're bill's friends from the UK"
    print mystr.capitalize()
    

    출력 : John, they're bill's friends from the uk

    str.capitalize()는 str의 첫 글자만을 대문자로, 나머지는 전부 소문자로 바꾼 str을 return해 줍니다.

    2. 문장의 모든 단어의 첫 글자를 대문자로 바꾸는 경우 - str.title()

    mystr = "john, they're bill's friends from the UK"
    print mystr.title()
    

    출력 : John, They'Re Bill'S Friends From The Uk

    str.title()는 모든 단어의 첫 글자를 대문자로, 그 외의 글자는 소문자로 변환한 str을 return합니다. 이때 단어를 나누는 기준에 공백 문자 뿐만 아니라 따옴표나 큰 따옴표 등도 포함되어 있기 때문에, 스트링 안에 따옴표가 있는 경우는 주의해서 써야 합니다.

    3. str.title()을 보완한 string.capwords()

    import string
    mystr = "john, they're bill's friends from the UK"
    print string.capwords(mystr)
    

    출력 : John. They're Bill's Friends From The Uk

    string.capwords(s[, sep])

    1. str.split()으로 단어를 구분
    2. 각각의 단어에 str.capitalize()
    3. str.join()으로 단어를 붙임

    하는 방법으로 구현되어 있습니다. sep이 지정되지 않은 경우 공백 문자는 전부 스페이스(" ")하나로 바뀌니 주의해서 써주세요. sep을 지정한 경우 sepsplit()join()에서 쓰입니다

    import string
    mystr = "john.\nthey're bill's        friends from the UK"
    print "sep = None:\n", string.capwords(mystr)
    print "----------------"
    print "sep = '\\n':\n", string.capwords(mystr, "\n")
    

    결과 :

    sep = None:
    John. They're Bill's Friends From The Uk
    ----------------
    sep = '\n':
    John.
    They're bill's        friends from the uk
    

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

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

(ಠ_ಠ)
(ಠ‿ಠ)