파이썬에서 앞 뒤 공백 문자 제거 하기

조회수 10076회

스트링에서 앞 뒤의 공백 문자를 제거하고 싶어요 예를 들면

" Hello " --> "Hello"
" Hello"  --> "Hello"
"Hello "  --> "Hello"
"Bob has a cat" --> "Bob has a cat"

이렇게요.

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    앞 뒤 공백 문자 하나만 제거하고 싶은 건가요 아니면 여러 개를 제거하고 싶으신가요?

    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---------
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)