[알고리즘] replace 이용 알고리즘

Yoongja·2023년 9월 27일
post-thumbnail
'''
영어와 숫자가 무작위로 조합된 문자열 s를 매개변수로 주어지고, 이 s가 원래 의미하는 숫자로만 return 하도록 solution 함수를 완성
'''

s1 = "8zerothree2"
s2 = "seven73nine"
s3 = "two53eightfour"

def solution(s):
    dict = {
        "zero" : 0,
        "one" : 1,
        "two" : 2,
        "three" : 3,
        "four" : 4,
        "five" : 5,
        "six" : 6,
        "seven" : 7,
        "eight" : 8,
        "nine" : 9
        }
    for d in dict :
        s = s.replace(d,str(dict[d]))
    return int(s)

print(solution(s1))
print(solution(s2))
print(solution(s3))

핵심은 replace

replace 함수 설명
'변수. replace(old, new, [count])' 형식

  • old : 현재 문자열에서 변경하고 싶은 문자

  • new: 새로 바꿀 문자

  • count: 변경할 횟수. 횟수는 입력하지 않으면 old의 문자열 전체를 변경한다. 기본값은 전체를 의미하는 count=-1로 지정되어있다.

>>> 'oxoxoxoxox'.replace('ox', '*', 1)
*oxoxoxox
profile
Belief in the possibility

0개의 댓글