우와한 개발자

[Python] 파이썬 - 문자열 함수와 메서드 정리

by 우와한개발자

함수 vs 메소드 비교

구분 사용법 예시
함수 함수(객체) len(str), type(str), print(str)
메소드 객체.메소드() str.upper(), str.split(), str.replace()

 

1. 대소문자 변환

함수 설명 예시
upper() 모두 대문자로 "hello".upper() → "HELLO"
lower() 모두 소문자로 "HELLO".lower() → "hello"
capitalize() 첫 글자만 대문자 "hello world".capitalize() → "Hello world"
title() 각 단어 첫 글자 대문자 "hello world".title() → "Hello World"
swapcase() 대소문자 반전 "Hello".swapcase() → "hELLO"

 

2. 검색과 위치

함수 설명 예시
count(sub) 문자열 개수 세기 "hello".count('l') → 2
find(sub) 위치 찾기 (없으면 -1) "hello".find('l') → 2
rfind(sub) 오른쪽부터 찾기 "hello".rfind('l') → 3
index(sub) 위치 찾기 (없으면 에러) "hello".index('l') → 2
startswith(sub) ~로 시작하는지 "hello".startswith('he') → True
endswith(sub) ~로 끝나는지 "hello".endswith('lo') → True

 

3. 문자열 변경

함수 설명 예시
replace(old, new) 문자열 치환 "hello".replace('l', 'L') → "heLLo"
strip() 양쪽 공백 제거 " hi ".strip() → "hi"
lstrip() 왼쪽 공백 제거 " hi ".lstrip() → "hi "
rstrip() 오른쪽 공백 제거 " hi ".rstrip() → " hi"
zfill(width) 0으로 채우기 "42".zfill(5) → "00042"

 

4. 문자열 분리와 결합

함수 설명 예시
split() 문자열 나누기 "a b c".split() → ['a', 'b', 'c']
split(sep) 구분자로 나누기 "a,b,c".split(',') → ['a', 'b', 'c']
splitlines() 줄 단위로 나누기 "a\nb\nc".splitlines() → ['a', 'b', 'c']
join(list) 리스트를 문자열로 "-".join(['a', 'b']) → "a-b"

 

5. 정렬과 채우기

함수 설명 예시
center(width) 가운데 정렬 "hi".center(10) → " hi "
ljust(width) 왼쪽 정렬 "hi".ljust(10) → "hi "
rjust(width) 오른쪽 정렬 "hi".rjust(10) → " hi"
center(width, char) 문자로 채우기 "hi".center(10, '*') → "****hi****"

 

6. 문자열 확인 (판별)

함수 설명 예시
isalpha() 알파벳인지 "abc".isalpha() → True
isdigit() 숫자인지 "123".isdigit() → True
isalnum() 알파벳+숫자인지 "abc123".isalnum() → True
isspace() 공백인지 " ".isspace() → True
isupper() 대문자인지 "ABC".isupper() → True
islower() 소문자인지 "abc".islower() → True
istitle() 제목 형식인지 "Hello World".istitle() → True
isdecimal() 10진수인지 "123".isdecimal() → True
isnumeric() 숫자 형태인지 "Ⅲ".isnumeric() → True

 

7. 기타 유용한 함수

함수 설명 예시
len(str) 문자열 길이 len("hello") → 5
ord() 문자 → 아스키코드 ord('A') → 65
chr() 아스키코드 → 문자 chr(65) → 'A'
max(str) 가장 큰 문자 max("hello") → 'o'
min(str) 가장 작은 문자 min("hello") → 'e'
text = "  Hello, Python World!  "

# 1. 대소문자 변환
print(text.upper())           # "  HELLO, PYTHON WORLD!  "
print(text.lower())           # "  hello, python world!  "
print(text.title())           # "  Hello, Python World!  "

# 2. 공백 제거
print(text.strip())           # "Hello, Python World!"

# 3. 치환
print(text.replace('Python', 'Java'))  # "  Hello, Java World!  "

# 4. 검색
print(text.find('Python'))    # 9
print(text.count('o'))        # 3

# 5. 분리
words = text.strip().split()
print(words)                  # ['Hello,', 'Python', 'World!']

# 6. 결합
print('-'.join(['a', 'b', 'c']))  # "a-b-c"

# 7. 판별
print("123".isdigit())        # True
print("abc".isalpha())        # True
print("abc123".isalnum())     # True

# 8. 정렬
print("hi".center(10, '*'))   # "****hi****"
print("42".zfill(5))          # "00042"

 

자주 사용하는 함수 / 메서드

  • split() - 문자열 나누기
  • join() - 리스트를 문자열로
  • strip() - 공백 제거
  • replace() - 문자열 치환
  • upper() / lower() - 대소문자 변환
  • find() - 위치 찾기
  • count() - 개수 세기
  • startswith() / endswith() - 시작/끝 확인
  • isdigit() - 숫자 판별
  • format() / f-string - 포맷팅

 

블로그의 정보

우와한개발자 님의 블로그

우와한개발자

활동하기