[프로그래머스/python] 숫자 문자열과 영단어

romini·2021년 10월 19일
0

https://programmers.co.kr/learn/courses/30/lessons/81301

영단어와 숫자가 섞여있는 문자열을 최종적으로 숫자로 출력하는 문제

문자열을 반복문으로 돌려서

  • 변환할 필요 없는 숫자 그대로라면 answer에 바로 넣어주고

str.isdigit() : 문자열이 숫자로 구성되어 있는지를 true/false로 반환

  • 변환이 필요한 영단어라면 단어가 완성될 때까지 한 글자씩 연결시키면서 words 배열과 비교해 보고, 단어를 완성했다면 배열의 index를 answer에 넣어준다.

코드

def solution(s):
    answer = ''
    words = ['zero','one','two','three','four','five','six','seven','eight','nine']
    tmp = ''
    
    for v in s:
        if v.isdigit():
            answer += v
            continue
        else:
            tmp += v
            if tmp in words:
                answer += str(words.index(tmp))
                tmp = ''
            
    return int(answer)

0개의 댓글