문자열.replace() 함수는 다른 문자열의 일부를 대체하여 문자열을 생성하는 데 사용됩니다.
Python 문자열 대체
Python 문자열.replace() 함수 구문은 다음과 같습니다:
str.replace(old, new[, count])
원래 문자열은 수정되지 않은 채로 유지됩니다. 새 문자열은 substring old의 모든 발생을 new로 대체한 원래 문자열의 사본입니다. 선택적 인수 count
가 제공되면 첫 count 발생만 대체됩니다. 이 함수를 사용하여 문자열의 문자를 대체할 수도 있습니다.
Python 문자열.replace() 예제
문자열.replace() 함수를 사용하는 몇 가지 간단한 예제를 살펴보겠습니다.
s = 'Java is Nice'
# simple string replace example
str_new = s.replace('Java', 'Python')
print(str_new)
# replace character in string
s = 'dododo'
str_new = s.replace('d', 'c')
print(str_new)
출력:
Python is Nice
cococo
카운트로 Python 문자열 대체
s = 'dododo'
str_new = s.replace('d', 'c', 2)
print(str_new)
출력: cocodo
사용자 입력과 함께하는 String replace() 예제
input_str = input('Please provide input data\n')
delimiter = input('Please provide current delimiter\n')
delimiter_new = input('Please provide new delimiter\n')
output_str = input_str.replace(delimiter, delimiter_new)
print('Updated Data =', output_str)
출력:
Please provide input data
a,e,i,o,u
Please provide current delimiter
,
Please provide new delimiter
:
Updated Data = a:e:i:o:u
아래와 같이 str.replace() 함수를 사용할 수도 있습니다.
print(str.replace('abca', 'a', 'A'))
출력: AbcA
전체 스크립트 및 더 많은 Python String 예제는 GitHub 저장소에서 확인할 수 있습니다.
참고: API 문서
Source:
https://www.digitalocean.com/community/tutorials/python-string-replace