목차
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
반응형
'Python > 기초문법' 카테고리의 다른 글
[자료구조] 스택(Stack), 큐(Queue) (0) | 2023.05.17 |
---|---|
[기초문법] strip(), split() (0) | 2023.05.16 |
[기초문법] math : sqrt(), pow() 함수 (0) | 2023.05.06 |
[기초문법] reverse(), reversed() 함수 비교 (0) | 2023.01.25 |
[기초문법] len(), count() (0) | 2023.01.11 |