English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python 기본 튜토리얼

Python 흐름 제어

Python 함수

Python 데이터 타입

Python 파일 작업

Python 객체와 클래스

Python 날짜와 시간

Python 고급 지식

Python 참조 가이드

Python 문자열 replace() 사용법 및 예제

파이썬 문자열 메서드

replace() 메서드는 문자열에서 old(오래된 문자열)을 new(새 문자열)로 대체합니다. 세 번째 매개변수 count를 지정하면 count 번만 대체합니다.

replace()의 문법은 다음과 같습니다:

str.replace(old, new[, count])

replace() 매개변수

replace() 메서드는 최대로 사용할 수 있습니다3개의 매개변수:

  • old -대체하려는 오래된 서브 문자열

  • new -새로운 서브 문자열이 오래된 서브 문자열을 대체합니다

  • count(선택)-old 문자열을 new 문자열로 대체할 횟수

count가 지정되지 않으면, replace() 메서드는 모든出现的 old 문자열을 new 문자열로 대체합니다.

replace() 반환 값

replace() 메서드는 old 문자열이 new 문자열로 대체된 문자열의 복사본을 반환합니다. 원래 문자열은 변경되지 않습니다.

old 문자열이 찾지 못되면, 원래 문자열의 복사본을 반환합니다.

예제1replace()를 어떻게 사용하나요?

song = 'cold, cold heart'
print(song.replace('cold', 'hurt'))
song = 'Let it be, let it be, let it be, let it be'
'''두 번만 나타나는 'let'만 대체됩니다'''
print(song.replace('let', "don't let", 2))

이 프로그램을 실행할 때, 출력은 다음과 같습니다:

hurt, hurt heart
Let it be, don't let it be, don't let it be, let it be

String replace()에 대한 더 많은 예제

song = 'cold, cold heart'
replaced_song = song.replace('o', 'e')
# 원래 문자열은 변경되지 않았습니다
print('원래 문자열:', song)
print('대체된 문자열:', replaced_song)
song = 'let it be, let it be, let it be'
# 최대 0개의 문자열을 대체
# 원래 문자열의 복사본을 반환
print(song.replace('let', 'so', 0))

이 프로그램을 실행할 때, 출력은 다음과 같습니다:

원래 문자열: cold, cold heart
대체된 문자열: celd, celd heart
let it be, let it be, let it be

파이썬 문자열 메서드