반응형
파이썬(Python) 문자열 처리
<기본>
- split()
- strip()
- join()
- find(), count(), startswith(), endswith()
- replace()
1. 문자열 분리하기 - split()
str.split([sep])
- split() 메서드는 구분자 sep를 기준으로 str 문자열을 분리해 리스트로 반환
(예제)
"에스프레소,아메리카노,카페라테,카푸치노".split(',')
['에스프레소', '아메리카노', '카페라테', '카푸치노']
2. 불필요한 문자열 삭제하기 - strip()
str.strip([chars])
- 문자열에서 앞뒤 공백 혹은 개행문자와 같이 불필요한 부분을 지워야 할 때 사용
(예제)
"ㅁㅁPythonㅁㅁㅁ".strip('ㅁ')
'Python'
3. 문자열 연결하기 - join()
str.join(문자열1[,문자열2,문자열3, ... , 문자열n])
(예제1)
" ".join(["서울시","강남구","논현대로","120(논현동)"])
'서울시 강남구 논현대로 120(논현동)'
(예제2)
join_str = "\n".join(["서울시","강남구","논현대로","120(논현동)"])
join_str
'서울시\n강남구\n논현대로\n120(논현동)'
4. 문자열 찾기 - find(), count(), startswith(), endswith()
str.find(search_str[, start, end])
- 문자열(str)에서 검색문자열(search_str)과 첫 번째로 일치하는 문자열 위치를 반환
- 문자열의 위치는 0부터 시작
- 문자열에서 찾으려는 검색문자열(search_str)이 없으면 -1을 반환
str.count(search_str[, start, end])
- 문자열(str)에서 검색문자열(search_str)과 일치하는 문자열의 개수를 반환
str.startswith(prefix_str[, start, end])
- 문자열(str)이 지정한 문자열(prefix_str)로 시작하면 True를 반환하고, 아니면 False를 반환
str.endswith(suffix_str[, start, end])
- 문자열(str)이 지정한 문자열(suffix_str)로 끝나면 True를 반환하고, 아니면 False를 반환
5. 문자열 바꾸기 - replace()
str.replace(old_str, new_str[, count])
- 문자열(str)에서 지정한 문자열(old_str)을 찾아서 새로운 문자열(new_str)로 바꿉니다.
- count 옵션을 지정하지 않으면 문자열(str) 전체에서 찾아 바꿉니다.
(예제)
old_str = "Python is powerful, Python is easy. Python is open."
print(old_str.replace("Python", "IPython"))
print(old_str.replace("Python", "IPython", 2))
(결과)
IPython is powerful, IPython is easy. IPython is open.
IPython is powerful, IPython is easy. Python is open.
6. 대소문자 변경하기 - lower(), upper()
- 문자열에서 로마자 알파벳을 모두 소문자로 바구거나 대문자로 바꿀 수 있습니다.
str.lower()
str.upper()
(예제)
old_str = "Python is powerful, Python is easy. Python is open."
print(old_str.lower())
print(old_str.upper())
(결과)
python is powerful, python is easy. python is open.
PYTHON IS POWERFUL, PYTHON IS EASY. PYTHON IS OPEN.
반응형
'개발(IT) > Python(파이썬)' 카테고리의 다른 글
파이썬(Python) 데이터처리 - 판다스(pandas) #1 (1) | 2024.12.07 |
---|---|
파이썬(Python) 데이터처리 - 넘파이(NumPy) (0) | 2024.12.01 |
파이썬(Python) 파일 읽고(read) 쓰기(write) (0) | 2024.11.23 |
파이썬(Python) 스케줄러 패키지(Schedule Package) (0) | 2024.11.16 |
파이썬(Python) 패키지(Package) (0) | 2024.11.16 |