일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 레이아웃
- NATIVE
- graphql
- Notification
- 네비게이션
- navigation
- AWS
- ubuntu
- Python
- scope
- JavaScript
- 배포
- 후기
- 네이티브
- 리액트
- 스코프
- 자바스크립트
- Push
- EC2
- Express
- 변수
- 카카오
- github
- Background
- React
- MongoDB
- JS
- 알림
- 디자인
- 면접
Archives
- Today
- Total
어서와, 개발은 처음이지?
파이썬 replace() 문자열 제거, 수정(변환) 본문
반응형
1. 문자열 변경(replace)
파이썬은 문자열 변경을 할 수 있는 replace 함수를 제공합니다.
replace와 replaceAll이 나눠져있는 자바와 혼동될 때가 있어서 메모합니다.
replace()의 사용 방법은 아래와 같습니다.
replace(old, new, [count]) -> replace("찾을값", "바꿀값", [바꿀횟수])
text = '123,456,789,999'replaceAll= text.replace(",","")replace_t1 = text.replace(",", "",1)replace_t2 = text.replace(",", "",2)replace_t3 = text.replace(",", "",3)print("결과 :")print(replaceAll)print(replace_t1)print(replace_t2)print(replace_t3)'''결과 :123456789999123456,789,999123456789,999123456789999'''
2. 우측부터 변경
replace는 좌측부터 값을 변경하는데, 우측부터 count만큼 변경하고 싶으면 어떻게 해야하나 해서 text.replace(",", "", -1)라고 실행해봤는데 되지 않았습니다.
strip함수 (strip, lstrip, rstrip)에 인자를 넣어서 .rstrip(",") 로 오른쪽 문자열의 변경이 가능하지만 오른쪽 끝 글자에서만 동작하기 때문에 원하던 결과는 나오지 않았습니다.
파이썬 string문자열의 특성상 인덱싱으로 접근하여 값만 변경 불가능해서 (text[1]="A" -> 에러) 그냥 함수를 구현해봤습니다.
def replaceRight(original, old, new, count_right):repeat=0text = originalold_len = len(old)count_find = original.count(old)if count_right > count_find : # 바꿀 횟수가 문자열에 포함된 old보다 많다면repeat = count_find # 문자열에 포함된 old의 모든 개수(count_find)만큼 교체한다else :repeat = count_right # 아니라면 입력받은 개수(count)만큼 교체한다while(repeat):find_index = text.rfind(old) # 오른쪽부터 index를 찾기위해 rfind 사용text = text[:find_index] + new + text[find_index+old_len:]repeat -= 1return texttext = '123,456,789,999'#text.replace(",", "", -1); print(text) #안됨#text = replaceRight(text, ",", "", 2)print("결과 :")print(replaceRight(text, ",", "", 0))print(replaceRight(text, ",", "", 1))print(replaceRight(text, ",", "", 2))print(replaceRight(text, ",", "", 3))print(replaceRight(text, ",", "", 4))'''결과 :123,456,789,999123,456,789999123,456789999123456789999123456789999'''
'Python' 카테고리의 다른 글
파이썬 datetime 날짜 계산 (8) | 2018.07.23 |
---|