https://school.programmers.co.kr/learn/courses/30/lessons/12951
문제는 너무 간단하다.
처음에 문제를 풀 때는 각 단어별로 첫번째 문자는 대문자로, 그 뒤에 나머지 문자열은 하나하나 소문자로 바꿔주는 코드를 작성했다.
islower(), isupper(), lower(), upper() 등의 함수를 사용했는데, 너무 비효율적인 것 같아 구글링을 해보니 title과 capitalize라는 좋은 내장함수가 있어 기록하려 한다.
title() : 문장의 모든 단어의 첫 글자를 대문자로, 나머지는 소문자
capitalize(): 문장의 첫 글자만 대문자로, 나머지는 소문자
title의 경우 띄어쓰기 뿐만 아니라, 숫자나 특수기호 등, 알파벳 이외의 문자들을 기준으로 구분해서 첫 글자를 대문자로 바꿔준다.
우선 정답 코드는 아래와 같다.
def solution(s):
answer = ''
s=s.split(' ')
for i in range(len(s)):
# capitalize 내장함수를 사용하면 첫 문자가 알파벳일 경우 대문자로 만들고
# 두번째 문자부터는 자동으로 소문자로 만든다
# 첫 문자가 알파벳이 아니면 그대로 리턴한다
s[i]=s[i].capitalize()
answer=' '.join(s)
return answer
def solution2(s):
return s.title()
s = "abcd"
print(s.capitalize()) #result : 'Abcd'
print(s.title()) #result : 'Abcd'
s = "hello world, welcom to python"
print(s.capitalize()) #result : 'Hello world, welcom to python'
print(s.title()) #result : 'Hello World, Welcom To Python'
s = "a1b2c3"
print(s.capitalize()) #result : 'A1b2c3'
print(s.title()) #result : 'A1B2C3'
s = "abc-def gh"
print(s.capitalize()) #result : 'Abc-def gh'
print(s.title()) #result : 'Abc-Def Gh