Algorithm

[Python] 문자열 치환하는 방법 replace

띵지니어 2023. 4. 6. 21:32
    • replace

      str.replace(old, new[, count])
      모든 부분 문자열 old 가 new 로 치환된 문자열의 복사본을 돌려줍니다.
      선택적 인자 count 가 주어지면, 앞의 count 개만 치환됩니다.

      old : 바꾸고 싶은 문자열
      new : 새로 바꾸고 싶은 문자열
      count : 앞에서 부터 count 개수 만큼 문자 바꾸기



      예시 )
a = "hello world"
b = "abcd****efgh"
print(a.replace("hello", "hi"))
print(b.replace("*", "0"))       # 전부 변경
print(b.replace("*", "0", 2))    # 부분 변경 (앞에서 부터)

""" 
*output*

hi world
abcd0000efgh
abcd00**efgh

"""