[Python#46]숫자 문자열과 영단어

Gi Woon Lee·2024년 8월 24일
0

Python

목록 보기
6/13

2021카카오_숫자 문자열과 영단어

문제 컨셉

영단어와 숫자가 혼합된 형태의 문자열 데이터 s가 주어지면 해당 데이터를 숫자로 전부 바꿔주기를 원한다.

  • 예시:
    "one2three4five" -> 12345

방법: dictionary로 만들어서 해결!

  1. 상응하는 데이터를 dictionary 로 만든다.
  2. D.items() method + S.replace method 활용하여 모두 바꿔준다!

코드

s = "one2three456seveneight9"

def solution(s):
    # dictionary 생성
    dictionary = {
           'zero': 0,
           'one': 1,
           'two': 2,
           'three': 3,
           'four': 4,
           'five': 5,
           'six': 6,
           'seven': 7,
           'eight': 8,
           'nine':9}
    # items() method 사용 key-value 세트 하나씩 for문 돌리기
    for key, value in dictionary.items():
        # s.replace method는 argument로 str데이터가 와야 한다. 
        s = s.replace(key, str(value))
    # int() 함수로 integer 데이터로 변환
    return int(s)

solution(s)
# 123456789

알아야 할 개념들

  1. dictionary 만들기
  2. S.replace(argument1, argument2) 모든 인자는 string 데이터!
  3. D.items()
  4. int(): transform to integer data

0개의 댓글