스트링에 단어 첫 글자를 대문자로 바꾸는 방법에 대해서 알고싶습니다
조회수 9102회
1 답변
-
보통 앞글자만 대문자로 변환하는 경우는 다음의 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
str.split()
으로 단어를 구분- 각각의 단어에
str.capitalize()
str.join()
으로 단어를 붙임
하는 방법으로 구현되어 있습니다.
sep
이 지정되지 않은 경우 공백 문자는 전부 스페이스(" ")하나로 바뀌니 주의해서 써주세요.sep
을 지정한 경우sep
은split()
과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
댓글 입력