Python에서 strip()
을 이용하면 문자열에서 특정 문자를 제거할 수 있습니다.
Java 등의 다른 언어들도 strip()
을 제공하며, 기능은 모두 비슷합니다.
Python의 String은 다음 함수를 제공합니다.
strip([chars])
: 인자로 전달된 문자를 String의 왼쪽과 오른쪽에서 제거합니다.lstrip([chars])
: 인자로 전달된 문자를 String의 왼쪽에서 제거합니다.rstrip([chars])
: 인자로 전달된 문자를 String의 오른쪽에서 제거합니다.
인자를 전달하지 않을 수도 있으며, 인자를 전달하지 않으면 String에서 공백을 제거합니다.
공백(white space) 제거
다음 코드는 strip()
에 인자를 전달하지 않습니다.
인자를 전달하지 않으면 문자열에서 공백을 제거합니다.
text = ' Water boils at 100 degrees '
print('[' + text.rstrip() + ']')
print('[' + text.lstrip() + ']')
print('[' + text.strip() + ']')
결과
[ Water boils at 100 degrees]
[Water boils at 100 degrees ]
[Water boils at 100 degrees]
동일한 문자 제거
인자로 문자 1개를 전달하면 그 문자와 동일한 것을 모두 제거합니다. 동일하지 않은 문자가 나올 때까지 제거합니다.
text = '0000000Water boils at 100 degrees 000'
print(text.lstrip('0'))
print(text.rstrip('0'))
print(text.strip('0'))
결과
Water boils at 100 degrees 000
0000000Water boils at 100 degrees
Water boils at 100 degrees
여러 문자 제거
인자로 여러 문자를 전달하면 그 문자들과 동일한 것들을 모두 제거합니다. 동일하지 않은 문자가 나올 때까지 제거합니다.
text = ",,,,,123.....water....pp"
print(text.lstrip(',123.p'))
print(text.rstrip(',123.p'))
print(text.strip(',123.p'))
결과
water....pp
,,,,,123.....water
water
다음 예제도 위와 동일하게 여러 문자를 인자로 전달하였습니다.
text = ' Water boils at 100 degrees '
print(text.lstrip(' Water'))
print(text.rstrip(' degrees '))
print(text.strip(' degrees '))
boils at 100 degrees
Water boils at 100
Water boils at 100
참고
Loading script...
Related Posts
- numpy.arange(), 균일 간격 배열
- numpy.concatenate(), 배열 합치기
- numpy hstack, vstack 함수 (배열 연결)
- numpy.average(), 배열 가중 평균
- Numpy 배열을 List로 변환
- 파이썬 List를 Numpy 배열로 변환
- numpy flatten() 함수, 1차원 배열로 변환(평탄화)
- numpy의 min(), max() 함수 (최소, 최대 값)
- numpy.mean(), 배열 평균 계산
- numpy.log(), 로그 함수 사용 방법
- numpy.shape(), 배열 크기/형태/차원 확인
- numpy.sqrt(), 배열의 제곱근 계산
- numpy.zeros(), 0으로 채워진 배열 생성
- Python Numpy 버전 확인 방법
- numpy.argsort(), 배열 정렬
- numpy.clip(), 배열의 최대/최소 값 지정
- numpy.linspace(), 동일 간격 숫자 배열
- Numpy - random 모듈, 난수 배열 생성
- Numpy의 ndarray 사용 방법 알아보기
- numpy.transpose(), 전치 행렬 변환
- Numpy - where() 사용 방법
- Python - numpy.append(), 배열 추가
- Python numpy.random.choice(), 랜덤 샘플링
- Python numpy.reshape(), 배열 차원 변경
- Python numpy.sum(), 배열의 합
- Python numpy.unique(), 배열 중복 제거
- Python - json.dumps()로 JSON 출력하기
- Python - find() 문자 위치 찾기
- Python lower() 문자열 소문자로 변환
- Python upper() 문자열 대문자로 변환
- Python 에러 해결, 'conda' 용어가 cmdlet, 함수, 스크립트 ... 인식되지 않습니다.
- Python 에러 해결, AttributeError: module 'jwt' has no attribute 'encode'
- Python - assert 사용 방법
- Python - Counter로 Collection 개수 세기
- Python - enumerate(), for/index 예제