문자열에서 특정문자 입력후 대문자로 바꾸기

조회수 1373회
InputStr=input('Input a sentence :')
Inputfind=input('Input a word for search :')
findLength=len(Inputfind)

Index=InputStr.find(Inputfind)



if Index==-1:
    print('바꿀 문자가 없다.')
else:
    beforeStr=InputStr[0:Index]
    changeStr=InputStr[Index:Index+findLength].upper()
    afterStr=InputStr[Index+findLength:]
    result=beforeStr+changeStr+afterStr
    print(result)
    print('A word "',Inputfind,'" apperas',InputStr.count(Inputfind),'times in the sentence.')

위 코드대로 하면 첫번째 단어만 대문자로 바꾸고 그뒤는 실행이안되서,

ex) power overwhelming 을 입력하면 powER overwhelming 이라고 나옵니다.

powER ovERwhelming 이라고 나오게 하고싶은데 어떻게 고쳐야하나요.

  • find() 함수로 찾은 문자열이 하나 일 경우에만 처리를 해서 그렇습니다. 여러 개일 경우를 생각해서 수정하면 되겠네요 알 수 없는 사용자 2019.10.11 11:42

1 답변

  • str의 find method는 argument로 문자열, 시작 index, 끝 index 를 받아서 문자열이 처음 찾아지는 위치를 반환 하는 method 입니다.

    따라서, 위의 소스는 입력받은 문자열에서 찾기를 원하는 문자열이 일치하는 첫번째 위치만 반환 하기 때문에 처음 발견된 문자열만 변환 하게 됩니다.

    위의 소스를 원하는 결과가 나오도록 고치는 두가지 방법이 있습니다.

    1. 첫번 째 방법
      • 찾는 문자열을 전체 문자열에서 한개 찾은 후, 그 찾은 위치의 다음 문자열부터 다시 찾기를 반복 해서 더이상 찾는 문자열이 전체 문자열에서 없을 때까지 반복 하면서 수행하도록 수정 하는 방법
    InputStr=input('Input a sentence :')
    Inputfind=input('Input a word for search :')
    indexes = []
    start, end = 0, len(InputStr)
    while True:
        index = InputStr.find(Inputfind, start, end)
        if index == -1:
            break
        indexes.append(index)
        start = index+len(Inputfind)
    InputStr = list(InputStr)
    for i in indexes:
        InputStr[i:i+len(Inputfind)] = list(Inputfind.upper())
    
    if not indexes:
        print('바꿀 문자가 없다.')
    else:
        print(''.join(InputStr))
        print('A word "',Inputfind,'" apperas', len(indexes),'times in the sentence.')
    
    1. 두번 째 방법
      • replace를 사용 하는 방법
    InputStr=input('Input a sentence :')
    Inputfind=input('Input a word for search :')
    findLength=len(Inputfind)
    Index=InputStr.find(Inputfind)
    
        if Index==-1:
            print('바꿀 문자가 없다.')
        else:
            result = InputStr.replace(Inputfind, Inputfind.upper())
            print(result)
            print('A word "',Inputfind,'" apperas',InputStr.count(Inputfind),'times in the sentence.')
    
    • (•́ ✖ •̀)
      알 수 없는 사용자

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

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

(ಠ_ಠ)
(ಠ‿ಠ)