m → rn으로
#내 풀이
def solution(rny_string):
answer = ''
for i in rny_string:
if i == "m":
answer += "rn"
else:
answer += i
return answer
#다른 사람 풀이
def solution(rny_string):
return rny_string.replace('m', 'rn')
replace()
문자열의 특정 부분을 다른 문자열로 교체할 때 사용하는 메서드
# 1. 기본 사용법
text = "hello world"
new_text = text.replace("hello", "hi")
# "hi world"
2. 특정 횟수만 바꾸기
replace(old, new, count)
text = "apple apple apple"
new_text = text.replace("apple", "banana", 2)
print(new_text) # "banana banana apple"
3. 여러 개 바꾸기
replace()를 여러 번 호출하거나,
또는 딕셔너리와 for문 활용
text = "I like cats and dogs"
text = text.replace("cats", "tigers").replace("dogs", "wolves")
print(text) # "I like tigers and wolves"
또는 딕셔너리 활용:
replacements = {"cats": "tigers", "dogs": "wolves"}
text = "I like cats and dogs"
for old, new in replacements.items():
text = text.replace(old, new)
4. 공백이나 특정 문자 제거
text = " hello "
print(text.replace(" ", "")) # "hello" (모든 공백 제거)
# 양쪽 공백만 제거하고 싶다면 strip()이 더 적절.
print(text.strip()) # "hello"
5. 리스트에서 replace() 사용하기
replace()는 문자열 메서드라 리스트에는 직접 사용할 수 없음.
리스트의 각 요소에 replace()를 적용하려면 리스트 컴프리헨션을 사용하면 됨.
words = ["hello world", "goodbye world"]
new_words = [word.replace("world", "Python") for word in words]
print(new_words) # ['hello Python', 'goodbye Python']
strip()
strip()은 문자열 양쪽 끝의 공백이나 특정 문자를 제거하는 메서드임.
# 기본 사용법: 양쪽 끝의 공백 제거
text = " hello "
print(text.strip()) # "hello"
특정 문자 제거하기
# 양쪽 끝에서 특정 문자 제거
text = "***hello***"
print(text.strip("*")) # "hello"
'프로그래밍 > 프로그래머스' 카테고리의 다른 글
[파이썬/python] 약수의 개수와 덧셈 - 제곱수는 약수의 갯수가 홀수. (0) | 2025.03.10 |
---|---|
[파이썬/python] 프로그래머스 문자열 겹쳐쓰기 (0) | 2025.03.09 |
[파이썬/python] 프로그래머스 정수 부분 (0) | 2025.03.09 |