코딩테스트/Python 개념

[Python] 문자열 제거 stirp()

박소민 2022. 2. 5. 14:05
strip()
  : 문자열에서 특정 문자 제거
  • strip('문자'): 인자로 전달된 문자를 String의 왼쪽, 오른쪽에서 제거
  • lstrip('문자'): 인자로 전달된 문자를 String의 왼쪽에서 제거
  • rstrip('문자'): 인자로 전달된 문자를 String의 오른쪽에서 제거

 

  • 공백 제거
    • strip() 에 인자를 전달하지 X
text=' Hello World '
print('['+ text.lstrip() + ']')
print('['+ text.rstrip() + ']')
print('['+ text.strip() + ']')

- 결과

[Hello World ]
[ Hello World]
[ Hello World ]

 

  •  동일한 문자 제거
    • 인자로 문자 1개 전달하면 다른 문자가 나올 때까지 주어진 문자 제거
text='00000Hello World 00'
print('['+ text.lstrip('0') + ']')
print('['+ text.rstrip('0') + ']')
print('['+ text.strip('0') + ']')

-결과

[Hello World 00]
[00000Hello World ]
[Hello World ]

 ※ 제일 끝 문자가 인자가 아닌 경우는 생략되지 않음

text=' 00000Hello World 002'
print('['+ text.lstrip('0') + ']')
print('['+ text.rstrip('0') + ']')
print('['+ text.strip('0') + ']')
  •  결과
[ 00000Hello World 002]
[ 00000Hello World 002]
[ 00000Hello World 002]

 

  • 여러 문자 제거
    • 인자로 여러 문자를 전달하면 그 문자들과 동일한 것 모두 제거
    • 동일하지 않은 문자가 나올 때까지 제거
    • 전달된 여러 문자에 포함되어 있는 것들끼리 연결만 되어 있으면 삭제/ 띄워져 있으면 삭제 X
text=',,,,,123...Hello World 2..p'
print('['+ text.lstrip(',123.p') + ']')
print('['+ text.rstrip(',123.p') + ']')
print('['+ text.strip(',123.p') + ']')

- 결과

[Hello World 2..p]
[,,,,,123...Hello World ]
[Hello World ]

 

 

참고) codechacha.com