python

[python] 문자열 처리함

bbiyak2da 2025. 5. 22. 16:59

문자열 처리함

 

Python의 문자열 처리 함수는 문자열을 조작하고 분석하기 위한 다양한 기능을 제공합니다.

문자열(str)은 변경 불가능한(immutable) 시퀀스 자료형으로, 많은 내장 메서드를 지원합니다.

 

Python의 문자열 처리 함수는 검색, 대소문자 변환, 정렬, 분리/합치기, 속성 확인 등 문자열을 다양하게 조작할 수 있게 해줍니다.

 

📌 1. 대소문자 처리 함수

upper() 모두 대문자로 "hello".upper() → 'HELLO'
lower() 모두 소문자로 "HELLO".lower() → 'hello'
capitalize() 첫 글자만 대문자 "python".capitalize() → 'Python'
title() 각 단어의 첫 글자 대문자 "python programming".title() → 'Python Programming'
swapcase() 대↔소문자 전환 "PyThOn".swapcase() → 'pYtHoN'

 

📌 2. 공백 및 정리 함수

strip() 양쪽 공백 제거 ' hi '.strip() → 'hi'
lstrip() 왼쪽 공백 제거 ' hi'.lstrip() → 'hi'
rstrip() 오른쪽 공백 제거 'hi '.rstrip() → 'hi'

 

📌 3. 검색/위치 관련 함수

find(sub) 서브 문자열 처음 위치 반환 (없으면 -1) 'hello'.find('l') → 2
index(sub) find와 같지만, 없으면 오류 발생 'hello'.index('l') → 2
count(sub) 서브 문자열 개수 'banana'.count('a') → 3
startswith(sub) 지정 문자열로 시작하는지 확인 'hello'.startswith('he') → True
endswith(sub) 지정 문자열로 끝나는지 확인 'hello'.endswith('lo') → True

 

📌 4. 변환 및 치환 함수

replace(old, new) 문자열 치환 'hello world'.replace('world', 'Python') → 'hello Python'
split(sep) 구분자로 나누어 리스트로 반환 'a,b,c'.split(',') → ['a', 'b', 'c']
join(list) 리스트 요소들을 연결하여 문자열 생성 ','.join(['a', 'b', 'c']) → 'a,b,c'

 

📌 5. 형식 관련 함수

zfill(n) n자리가 되도록 0으로 채움 '7'.zfill(3) → '007'
center(width) 가운데 정렬 'hi'.center(5) → ' hi '
ljust(width) 왼쪽 정렬 'hi'.ljust(5) → 'hi '
rjust(width) 오른쪽 정렬 'hi'.rjust(5) → ' hi'

 

📌 6. 문자열 속성 확인 함수

isalpha() 모두 알파벳인지 'abc'.isalpha() → True
isdigit() 모두 숫자인지 '123'.isdigit() → True
isalnum() 알파벳+숫자인지 'abc123'.isalnum() → True
isspace() 모두 공백인지 ' '.isspace() → True
islower() 모두 소문자인지 'abc'.islower() → True
isupper() 모두 대문자인지 'ABC'.isupper() → True

 

실습

python = "Python is Amazing"
print(python.lower())
print(python.upper())
print(python[0].isupper())
print(len(python))
print(python.replace("Python", "Java"))

index = python.index("n")
print(index)
index = python.index("n", index + 1)
print(index)

print(python.count("n"))

 

python is amazing
PYTHON IS AMAZING
True
17
Java is Amazing


5
15


2

 

python = "Python is Amazing"
print(python.find("Java"))
print(python.index("Java"))

 

-1
Traceback (most recent call last):
  File "c:\Users\블라블라\PythonWorkspace\practice.py", line 3, in <module>
    print(python.index("Java"))
          ~~~~~~~~~~~~^^^^^^^^
ValueError: substring not found

 

 

`find()` 함수는 찾는 문자열이 없을 경우 오류를 발생시키지 않고 `-1`을 반환합니다.

반면, `index()`는 찾는 값이 없으면 오류를 발생시킵니다.

 

차이점 알아두기!