파이썬에서 앞 뒤 공백 문자 제거 하기
조회수 10076회
스트링에서 앞 뒤의 공백 문자를 제거하고 싶어요 예를 들면
" Hello " --> "Hello"
" Hello" --> "Hello"
"Hello " --> "Hello"
"Bob has a cat" --> "Bob has a cat"
이렇게요.
1 답변
-
앞 뒤 공백 문자 하나만 제거하고 싶은 건가요 아니면 여러 개를 제거하고 싶으신가요?
1. 하나만 제거할 경우
def strip_one(s): if s.endswith(" ") : s = s[:-1] #마지막이 " "임을 검사 if s.startswith(" ") : s = s[1:] #첫번째가 " "임을 검사 return s a = " hello " print strip_one(a)
2. 여러 개를 제거할 경우 - str.strip([chars])
str.strip([chars])
은 스트링 맨앞/뒤의chars
를 찾아 제거합니다.chars
를 지정하지 않은 경우 모든 종류의 공백 문자를 제거하니 " "만 제거하고 싶다면 strip(" ")과 같이 사용하세요.a = " hello\nworld\n" print "--strip(' ') start---" print a.strip(" ") print "---------end---------" print "----strip() start----" print a.strip() print "---------end---------"
결과는
--strip(' ') start--- hello world ---------end--------- ----strip() start---- hello world ---------end---------
댓글 입력