[python] string strip method



strip method

strip은 특정 문자열에서 인수(제거하고자하는 문자)를 기준으로 문자열의 앞,뒤 문자를 모두 제거

Syntax

str.strip([chars])


Parameter

chars (optional): 문자열에서 제거할 문자 또는 문자 집합

- chars를 지정하지 않을 수 있으며, 그럴 경우에는 공백(white-space)를 제거


Return Values

chars에 설정된 인수를 제거한 뒤 새로운 문자열을 반환

- 인수가 제거하고자하는 문자열과 일치하지 않으면 문자를 제거하지 않음
- 인수가 제거하고자하는 문자열과 일치하면 일치하는 문자를 제거


Example

string = " ex example sentence "
print("string: {0}".format(string))

# chars 매개변수가 비었기 때문에 default white-space를 제거
print("string.strip(): {0}".format(string.strip()))

# chars 'exam'이 입력되었지만 string 앞뒤에는 공백이 존재하기 때문에 exam을 제거하지 않음
print("string.strip('exam'): {0}".format(string.strip('exam')))

# chars ' exam'이 입력되었기 때문에 string 앞뒤에 존재하는 공백과 e x a m 문자를 제거
print("string.strip(' exam'): {0}".format(string.strip(' exam')))

# chars에 입력되는 인수 순서와 상관 없이 string 앞뒤에 존재하는 문자 제거 (' exam' == 'xema ')
print("string.strip('xema '): {0}".format(string.strip('xema ')))

# 출력
# string:    ex example sentence 
# string.strip(): ex example sentence
# string.strip('exam'):    ex example sentence 
# string.strip(' exam'): ple sentenc
# string.strip('xema '): ple sentenc


참고문헌

[1] https://docs.python.org/3/library/stdtypes.html
[2] https://www.geeksforgeeks.org/python-string-strip-2/

댓글

이 블로그의 인기 게시물

[opencv-python] 이미지 크기조절(resize) 하는 법

[python] selenium close와 quit 차이점

[python]파이썬: csv reader header skip (첫번째 행 무시하기, 안읽기)