𝘼𝙣𝙖𝙡𝙮𝙨𝙞𝙨/ᴀʟɢᴏʀɪᴛʜᴍ
[Programmers] 특정 문자 제거하기
콜라맛갈비
2023. 3. 31. 12:14
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/120826
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
def solution(my_string, letter):
answer = my_string.replace(letter, '')
return answer
문자열 특정 문자 삭제하는 방법
1.
- 양 끝 공백 삭제 : text.strip()
- 양 끝 특정 단어 삭제 : text.strip(".") / text.strip("a""b""c")
- 오른쪽 끝 특정 단어 삭제 : text.rstip()
- 오른쪽 끝 특정 단어 삭제 : text.rstrip(".") / text.rstrip("a""b""c")
- 왼쪽 끝 특정 단어 삭제 : text.lstip()
- 왼쪽 끝 특정 단어 삭제 : text.lstrip(".") / text.lstrip("a""b""c")
2.
- 특정 문자열 치환 : text.replace("a", "")
''' 개행 코드가 섞여 있어도 한 번에 치환(삭제)할 수 있다. '''
tanka = '안녕하세요\r\n감사합니다\n수고하세요\r\n안녕히가세요\n실례합니다'
print(tanka)
print(tanka.replace('\r\n', '').replace('\n', ''))
#결과
#안녕하세요
#감사합니다
#수고하세요
#안녕히가세요
#실례합니다
#안녕하세요감사합니다수고하세요안녕히가세요실례합니다
3.
- 여러 개의 문자열 삭제 : translate
text ="translate、allows・us・to・delete・multiple・letters。"
table = text.maketrans({
'、': ' ', #왼쪽은 치환하고 싶은 문자, 오른쪽은 새로운 문자
'。': '.', #왼쪽은 치환하고 싶은 문자, 오른쪽은 새로운 문자
'・': ' ', #왼쪽은 치환하고 싶은 문자, 오른쪽은 새로운 문자
})
print(text)
print(text.translate(table))
#결과
#translate、allows・us・to・delete・multiple・letters。
#translate allows us to delete multiple letters.
4.
- re.sub
import re
text = "abc123def456ghi"
new_text = re.sub(r"[a-z]", "", text)
print(new_text)
#결과
#123456
728x90