파이썬/파이썬(python) 중급

[24-8 파이썬] replace(old, new)

Olivia-BlackCherry 2022. 9. 4. 17:42

replace 매서드는 문자열 매서드이다.

특정 문자를 새로운 문자로 바꿔주는 역할을 한다. 

 

string.replace(oldvalue, newvalue, count)

string= 원본

oldvalue = 바꾸고자 하는 문자

newvalue= 바꿀 문자

 

 

string.replace(old, new)
new = "I got up 6am.".replace("I", "You")
print(new)

I를 YOU로 바꿨다.

 

string.replace(old, new, count)
string = "Dear my friend, Dear my parents, Dear my sister, Dear my brother, Dear my teacher"
new = string.replace("Dear", "To", 2)
print(new)

count = count 값이 있다면, 최초로 나타난 oldvalue를 count 수 만큼 newvalue로 바꿔준다. 

Dear 2개를 To로 바꿨다. 3번째 Dear은 바뀌지 않았다.