Python/기초문법

[기초문법] replace 함수

gangee 2023. 5. 8. 15:07

목차

    728x90
    반응형

    replace 함수

    • 문자열을 변경하는 함수

    1. 사용 방법

    • str.replace(x, y, z)
    • x : 현재 문자열에서 변경하고 싶은 문자
    • y : 새롭게 변경 할 문자
    • z : 횟수(현재 문자열에서 변경하고 싶은 문자가 여러개 일 경우 치환할 횟수, 생략 가능)

    2. 사용 예시

    • 횟수 지정 없을 때
    str = 'hello world'
    str_1 = str.replace('h', 'o')
    str_2 = str.replace('o', 'y')
    str_3 = str.replace('hello', 'hi')
    str_4 = str.replace('w', 'hello')
    
    print(str_1)
    print(str_2)
    print(str_3)
    print(str_4)
    ---------------------------------------
    > oello world
    > helly wyrld
    > hi world
    > hello helloorld
    • 횟수 지정 있을 때
    str = 'a, a, a, b, c, c, b'
    
    str_1 = str.replace('a', 'x', 1)
    str_2 = str.replace('a', 'x', 2)
    str_3 = str.replace('b', 'y', 2)
    
    print(str_1)
    print(str_2)
    print(str_3)
    ----------------------------------------
    > x, a, a, b, c, c, b
    > x, x, a, b, c, c, b
    > a, a, a, y, c, c, y
    728x90
    반응형