TIL no.93 - Kata - Python - 3 - Credit Card Mask

박준규·2019년 12월 15일
0

Kata

목록 보기
3/4

1. Question

Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.

Your task is to write a function maskify, which changes all but the last four characters into '#'.

Example

maskify("4556364607935616") == "############5616"
maskify(     "64607935616") ==      "#######5616"
maskify(               "1") ==                "1"
maskify(                "") ==                 ""

# "What was the name of your first pet?"
maskify("Skippy")                                   == "##ippy"
maskify("Nananananananananananananananana Batman!") == "####################################man!"

2. My Solution

def maskify(cc):
    if len(cc)<5:
        return cc
    return "#"*len(cc[:-4])+cc[-4:]

뒤에서 4개까지의 문자열은 제외하고 나머지는 '#'으로 치환하는 문제입니다.

한가지 부끄러운 것은 문제를 문자 그대로 받아들여 푸는데 한참을 돌아갔습니다.

처음엔 치환이니 replace 메서드를 사용해야 겠다고 생각했고 그럼 모든 문자를 치환해야하니 정규표현식을 써야겠구나 하고 re.sub() 메서드를 사용하며 풀었으나 문득 위의 방법이 떠올랐습니다.

역시 Input과 Output에 집중하는 것이 중요하다는 것을 다시 한번 깨달았습니다.

3. Best Solution

def maskify(cc):
    return "#"*(len(cc)-4) + cc[-4:]

Python은 string에 음수를 곱하면 빈 문자열을 return합니다.

또한, 문자열의 길이를 벗어나게 slicing을 하더라도 유연하게 대처합니다.

Python의 이런 편리한 특성들을 복기하는 좋은 기회였습니다.

profile
devzunky@gmail.com

0개의 댓글