Languages/Python

[프로그래머스] 특정 문자 제거하기 (python)

genie0000 2025. 4. 23. 00:46
link icon

💻 프로그래머스 - 특정 문자 제거하기

👉 문제 보러 가기

 

🧩문제 설명

특정 문자 제거하기 문제

🧩문제 요약

이 문제는 주어진 문자열에서 특정 문자를 모두 제거하는 문제입니다.

  • 문자열에서 특정 문자를 빈 문자열로 교체하여 제거합니다.
  • replace() 메서드를 사용하여, my_string에서 letter를 빈 문자열로 교체합니다.

 


🔍 풀이 코드 1

def solution(my_string, letter):
    answer = ''
    for i in range(len(my_string)):
        if my_string[i] == letter:
            answer += ''
        else:
            answer += my_string[i]
    return answer

 

🔍 풀이 코드 2

def solution(my_string, letter):
    return my_string.replace(letter, "")

my_string.replace(letter, "")

  • Python의 replace() 메서드를 사용하면 문자열에서 특정 문자를 다른 문자로 간단하게 치환할 수 있습니다.
    이때, letter를 빈 문자열("")로 바꾸면 문자가 제거된 것과 같은 효과를 볼 수 있습니다.

 


 마무리 정리

 replace()

string.replace(old, new, count)
  • old: 바꿀 문자열 (필수)
  • new: old를 교체할 새로운 문자열 (필수)
  • count: 교체할 최대 횟수. 지정하지 않으면 모든 old를 교체 (선택사항)
    • 특정 문자를 제거할 때는 new를 빈 문자열 ""로 설정하면 됩니다.
    • 예를 들어, "hello".replace("e", "")는 "hllo"를 반환합니다.
text = "aaaaa"
result = text.replace("a", "b", 3)
print(result)  # "bbbaaa"

 

  • "a"를 "b"로 최대 3번만 교체하여 "bbbaaa"가 반환됩니다.

 

 

 

 


📌 아직 배우는 중이라 부족한 부분이 있을 수 있습니다.
혹시 잘못된 내용이나 더 나은 방법이 있다면 알려주세요 🙏
감사합니다! 😄