[프로그래머스 Lv1] 숫자 문자열과 영단어 (파이썬)

Jewon Joel Park·2022년 6월 1일
0

Programmers-solution

목록 보기
9/34

문제 링크


문제 설명

주어진 영문 및 숫자 문자열에서 숫자에 해당하는 문자열을 숫자로 치환하여 정수값을 반환하는 함수 작성


풀이 코드

chart = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}
def solution(s):
    for key, value in chart.items():
        if key in s:
            s = s.replace(key, str(value))
    return int(s)
chart = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
def solution(s):
    for idx, item in enumerate(chart):
        if item in s:
            s = s.replace(item, str(idx))
    return int(s)

코드 설명

  1. chart에 영문자열을 key, 해당하는 숫자를 value로 갖는 dict() 생성
  2. chart.items()key, value를 언패킹하여 해당 문자열이 주어진 문자열 내에 존재하는지를 판별 후 해당 문자열에서 keystr(value)로 치환
  3. 반환받는 타입은 정수형이므로 int(s)를 return
profile
10년을 돌고 돌아 마침내 제자리를 찾은 문과 출신 Python 개발자의 인생기록장

0개의 댓글