python String method 파이썬 문자열 메소드

2025. 5. 10. 22:50IT & Programming/python

파이썬 문자열 메소드

파이썬의 문자열(string)은 풍부한 메소드를 제공하여 텍스트 처리를 쉽게 할 수 있습니다. 다음은 주요 문자열 메소드들을 카테고리별로 정리한 것입니다.

1. 대소문자 변환

  • upper(): 모든 문자를 대문자로 변환
  • lower(): 모든 문자를 소문자로 변환
  • capitalize(): 첫 글자만 대문자로, 나머지는 소문자로 변환
  • title(): 각 단어의 첫 글자를 대문자로 변환
  • swapcase(): 대소문자를 서로 바꿈
s = "Hello, World!"
print(s.upper())       # HELLO, WORLD!
print(s.lower())       # hello, world!
print(s.capitalize())  # Hello, world!
print(s.title())       # Hello, World!
print(s.swapcase())    # hELLO, wORLD!

2. 검색 및 치환

  • count(sub[, start[, end]]): 부분 문자열의 등장 횟수 반환
  • find(sub[, start[, end]]): 부분 문자열의 첫 위치 반환 (없으면 -1)
  • rfind(sub[, start[, end]]): 부분 문자열의 마지막 위치 반환 (없으면 -1)
  • index(sub[, start[, end]]): find와 유사하지만 없으면 ValueError 발생
  • rindex(sub[, start[, end]]): rfind와 유사하지만 없으면 ValueError 발생
  • replace(old, new[, count]): 문자열 치환
s = "hello hello world"
print(s.count("hello"))          # 2
print(s.find("world"))           # 12
print(s.replace("hello", "hi"))  # hi hi world

3. 문자열 판별

  • isalpha(): 모든 문자가 알파벳인지 확인
  • isalnum(): 모든 문자가 알파벳 또는 숫자인지 확인
  • isdigit(): 모든 문자가 숫자인지 확인
  • isnumeric(): 모든 문자가 숫자 표현인지 확인
  • isdecimal(): 모든 문자가 10진수 숫자인지 확인
  • isspace(): 모든 문자가 공백인지 확인
  • islower(): 모든 문자가 소문자인지 확인
  • isupper(): 모든 문자가 대문자인지 확인
  • istitle(): 제목 형식인지 확인
print("abc".isalpha())    # True
print("abc123".isalnum()) # True
print("123".isdigit())    # True
print(" \t\n".isspace())  # True

4. 문자열 분할 및 결합

  • split([sep[, maxsplit]]): 구분자로 문자열 분할
  • rsplit([sep[, maxsplit]]): 오른쪽부터 문자열 분할
  • splitlines([keepends]): 줄바꿈으로 분할
  • partition(sep): 첫 구분자 기준으로 3부분으로 분할 (앞, 구분자, 뒤)
  • rpartition(sep): 마지막 구분자 기준으로 3부분으로 분할
  • join(iterable): 반복 가능한 객체의 요소들을 문자열로 연결
print("a,b,c".split(","))           # ['a', 'b', 'c']
print(",".join(["a", "b", "c"]))     # a,b,c
print("hello world".partition(" "))  # ('hello', ' ', 'world')

5. 공백 처리

  • strip([chars]): 양쪽 끝의 지정 문자(기본: 공백) 제거
  • lstrip([chars]): 왼쪽 끝의 지정 문자 제거
  • rstrip([chars]): 오른쪽 끝의 지정 문자 제거
print("  hello  ".strip())    # "hello"
print("  hello  ".lstrip())   # "hello  "
print("  hello  ".rstrip())   # "  hello"

6. 패딩 및 정렬

  • center(width[, fillchar]): 지정 폭에서 가운데 정렬
  • ljust(width[, fillchar]): 지정 폭에서 왼쪽 정렬
  • rjust(width[, fillchar]): 지정 폭에서 오른쪽 정렬
  • zfill(width): 지정 폭에서 0으로 채움
print("hello".center(11, '-'))  # ---hello---
print("hello".ljust(10, '*'))   # hello*****
print("hello".rjust(10, '*'))   # *****hello
print("42".zfill(5))            # 00042

7. 기타 메소드

  • startswith(prefix[, start[, end]]): 지정 접두사로 시작하는지 확인
  • endswith(suffix[, start[, end]]): 지정 접미사로 끝나는지 확인
  • expandtabs([tabsize]): 탭을 공백으로 변환
  • translate(table): 지정된 변환 테이블에 따라 문자 변환
  • encode([encoding[, errors]]): 문자열을 바이트 객체로 인코딩
print("hello".startswith("he"))  # True
print("hello".endswith("lo"))    # True
print("hello\tworld".expandtabs(4))  # "hello   world"

8. 문자열 서식

  • format(*args, **kwargs): 형식 지정자에 따라 문자열 포맷
  • format_map(mapping): 딕셔너리로 문자열 포맷
print("{} {}".format("hello", "world"))  # hello world
print("{name} {age}".format_map({"name": "John", "age": 30}))  # John 30

이러한 메소드들을 활용하면 파이썬에서 다양한 문자열 처리 작업을 효율적으로 수행할 수 있습니다.

반응형