
str.replace() 함수는 문자열 내에서 첫 번째로 발견한 searchValue를 replaceValue로 대체합니다. 만약 searchValue가 문자열 내에 여러 번 나타나면, 첫 번째로 발견한 searchValue만 대체됩니다.
예를 들어, 'hello world' 문자열에서 'world'를 'python'으로 바꾸고 싶다면, 다음과 같이 코드를 작성할 수 있습니다.
#hostingforum.kr
python
문자열 = 'hello world'
변경된 문자열 = 문자열.replace('world', 'python')
print(변경된 문자열) # 결과: 'hello python'
만약 모든 'world'를 'python'으로 바꾸고 싶다면, replace() 함수를 사용할 때 'world'이 여러 번 나타나는 경우를 대비하여 반복적으로 사용할 수 있습니다.
#hostingforum.kr
python
문자열 = 'hello world world'
변경된 문자열 = 문자열.replace('world', 'python')
print(변경된 문자열) # 결과: 'hello python python'
또는, replace() 함수를 여러 번 호출할 수 있습니다.
#hostingforum.kr
python
문자열 = 'hello world world'
변경된 문자열 = 문자열.replace('world', 'python').replace('world', 'python')
print(변경된 문자열) # 결과: 'hello python python'
하지만, 위의 방법은 불필요한 연산을 수행할 수 있습니다. 대신, 정규표현식을 사용하여 모든 'world'를 'python'으로 바꿀 수 있습니다.
#hostingforum.kr
python
import re
문자열 = 'hello world world'
변경된 문자열 = re.sub('world', 'python', 문자열)
print(변경된 문자열) # 결과: 'hello python python'
이 방법은 모든 'world'를 'python'으로 바꿀 수 있습니다.
2025-06-16 19:16