f_
frhyme.code
•python•⏱ 약 2분 소요

Python: strip string better with punctuation

1-line summary

  • 보통 strip()이라고 쓰지만, 여기에 parameter를 넘겨주면 넘어간 리스트의 모든 원소를 지워준다.

strip better

  • 사소합니다만, 보통 문자열의 양쪽 공백을 지워줄 때 다음과 같이 처리하죠.
"  frhyme...  ".strip()
  • 이게 다 인줄 알았는데, 이걸 이렇게 쓸 수도 있더군요. 아래와 같이 넘겨주면, “.”, “ “을 양쪽에서 모두 지워줍니다.
"  frhyme...  ".strip(" .")
  • 더 편하게 하려면 string 모듈에 있는 punctuation를 사용해서 처리할 수도 있죠.
import string 

print("--"*20)
print(f"== string.punctuation")
print(f"{string.punctuation}")
print("--"*20)
----------------------------------------
== string.punctuation
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
----------------------------------------
  • 다만, string.punctuation에는 스페이스(’ ’)가 없으므로 이를 채워서 다음처럼 변환해주는 것이 가장 좋습니다.
import string 
print("  ,#$%@#^frhyme...  ".strip(string.punctuation+" "))

reference

GitHub에서 이 글의 마크다운 원본 보기 & 수정 제안src/content/posts/2020-03-16-py_strip_string_punctuation

💡RELATED ARTICLES · 함께 읽으면 좋은 연관 포스트

글 주소가 클립보드에 복사되었습니다.