[Python] ord 함수 / 문자열 replace 메서드

송진수·2021년 7월 25일
1

프로그래머스 81301번 문제

다음은 숫자의 일부 자릿수를 영단어로 바꾸는 예시입니다.

  • 1478 → "one4seveneight"
  • 234567 → "23four5six7"
  • 10203 → "1zerotwozero3"

입력된 문자열에 섞인 문자와 숫자를 구분하여 모두 숫자로 변환하여 출력해야 한다.

처음에는 같은 문자형 데이터라도 ASCII 코드로 변환하면 구분할 수 있다는 점에 착안하여, 문자를 만나면 새로운 문자열에 문자를 추가하다가 리스트에 있는 단어가 완성되거나, 숫자를 만나는 경우 문자 만들기를 끝내고 초기화하는 방식을 이용했다.

def solution(s):
    answer = ''
    word = ''
    num_list = ['zero','one','two','three','four','five','six','seven','eight','nine']
    for ch in s:
        if ord(ch) > 57: # '0'~'9'의 ASCII 코드는 48~57
            word += ch
            if word in num_list:
                answer += str(num_list.index(word))
                word = ''
        else:
            if word in num_list:
                answer += str(num_list.index(word))
                word = ''
            answer += ch
    return int(answer)

하지만 파이썬은 스트링의 인덱스를 하나하나 뜯어볼 필요 없이 편리하게 문자열을 변환시킬 수 있는 replace 메서드를 제공한다!

'str'.replace(old, new, count=-1)

문자열 안에서 old로 주어진 문자열을 찾아 new로 바꾸어준다. count는 변환하는 횟수로, 기본값은 -1(모두 변환)이다.


# 리스트와 enumerate 함수를 활용해도 무방할 것이다.
# for num, word in enumerate(['zero','one', ... , 'eight', 'nine'] 이런 식으로..
num_dic = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"}

def solution(s):
    answer = s
    for key, value in num_dic.items():
        answer = answer.replace(key, value)
    return int(answer)
profile
보초

0개의 댓글