본문 바로가기

언어/Python

[ 파이썬 / Python ] str 클래스 사용하기

반응형

파이썬에서 문자열을 처리하는 다양한 내장 함수가 있습니다.
이러한 함수들은 문자열의 조작, 변환, 검색 등을 쉽게 할 수 있도록 도와줍니다.
아래에 주요 내장 함수와 메서드를 설명하겠습니다.

1. 문자열 메서드 목록

문자열 변환 메서드

  1. str.capitalize()
  • 문자열의 첫 번째 문자를 대문자로 변환
s = "hello"
print(s.capitalize())  # 출력: Hello
  1. str.casefold()
  • 문자열을 소문자로 변환 (locale-agnostic)
s = "Hello World"
print(s.casefold())  # 출력: hello world
  1. str.lower()
  • 문자열을 소문자로 변환
s = "Hello"
print(s.lower())  # 출력: hello
  1. str.upper()
  • 문자열을 대문자로 변환
s = "hello"
print(s.upper())  # 출력: HELLO
  1. str.title()
  • 문자열의 각 단어의 첫 글자를 대문자로 변환
s = "hello world"
print(s.title())  # 출력: Hello World
  1. str.swapcase()
  • 문자열의 대문자를 소문자로, 소문자를 대문자로 변환
s = "Hello World"
print(s.swapcase())  # 출력: hELLO wORLD

문자열 정렬 메서드

  1. str.center(width[, fillchar])
  • 문자열을 지정된 너비로 중앙에 맞춤. 필요시 fillchar로 채움
s = "hello"
print(s.center(10, '*'))  # 출력: **hello***
  1. str.ljust(width[, fillchar])
  • 문자열을 지정된 너비로 왼쪽 정렬. 필요시 fillchar로 채움
s = "hello"
print(s.ljust(10, '*'))  # 출력: hello*****
  1. str.rjust(width[, fillchar])
  • 문자열을 지정된 너비로 오른쪽 정렬. 필요시 fillchar로 채움
s = "hello"
print(s.rjust(10, '*'))  # 출력: *****hello

문자열 공백 처리 메서드

  1. str.strip([chars])
  • 문자열의 양쪽 끝에서 지정된 문자를 제거. 기본적으로 공백을 제거
s = "  hello  "
print(s.strip())  # 출력: "hello"
  1. str.lstrip([chars])
  • 문자열의 왼쪽 끝에서 지정된 문자를 제거. 기본적으로 공백을 제거
s = "  hello  "
print(s.lstrip())  # 출력: "hello  "
  1. str.rstrip([chars])
  • 문자열의 오른쪽 끝에서 지정된 문자를 제거. 기본적으로 공백을 제거
s = "  hello  "
print(s.rstrip())  # 출력: "  hello"

문자열 검색 메서드

  1. str.find(sub[, start[, end]])
  • 지정된 부분 문자열이 처음으로 나타나는 인덱스를 반환. 찾지 못하면 -1 반환
s = "hello"
print(s.find('l'))  # 출력: 2
  1. str.rfind(sub[, start[, end]])
  • 지정된 부분 문자열이 마지막으로 나타나는 인덱스를 반환. 찾지 못하면 -1 반환
s = "hello"
print(s.rfind('l'))  # 출력: 3
  1. str.index(sub[, start[, end]])
  • 지정된 부분 문자열이 처음으로 나타나는 인덱스를 반환. 찾지 못하면 예외 발생
s = "hello"
print(s.index('l'))  # 출력: 2
  1. str.rindex(sub[, start[, end]])
  • 지정된 부분 문자열이 마지막으로 나타나는 인덱스를 반환. 찾지 못하면 예외 발생
s = "hello"
print(s.rindex('l'))  # 출력: 3
  1. str.startswith(prefix[, start[, end]])
  • 문자열이 지정된 접두사로 시작하는지 확인
s = "hello"
print(s.startswith('he'))  # 출력: True
  1. str.endswith(suffix[, start[, end]])
  • 문자열이 지정된 접미사로 끝나는지 확인
s = "hello"
print(s.endswith('lo'))  # 출력: True

문자열 분할 및 결합 메서드

  1. str.split(sep=None, maxsplit=-1)
  • 문자열을 구분자로 분할하여 리스트로 반환
s = "hello world"
print(s.split())  # 출력: ['hello', 'world']
  1. str.rsplit(sep=None, maxsplit=-1)
  • 문자열을 구분자로 오른쪽부터 분할하여 리스트로 반환
s = "hello world"
print(s.rsplit())  # 출력: ['hello', 'world']
  1. str.splitlines([keepends])
  • 문자열을 줄바꿈 문자로 분할하여 리스트로 반환
s = "hello\nworld"
print(s.splitlines())  # 출력: ['hello', 'world']
  1. str.join(iterable)
  • 문자열의 각 요소를 특정 구분자로 결합
words = ["hello", "world"]
print(" ".join(words))  # 출력: hello world

문자열 대체 메서드

  1. str.replace(old, new[, count])
  • 문자열의 부분 문자열을 다른 문자열로 바꿈
s = "hello world"
print(s.replace('world', 'Python'))  # 출력: hello Python
  1. str.translate(table)
  • 변환 테이블을 사용하여 문자열을 대체
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
s = "this is string example....wow!!!"
print(s.translate(trantab))  # 출력: th3s 3s str3ng 2x1mpl2....w4w!!!

문자열 패딩 메서드

  1. str.zfill(width)
  • 문자열의 왼쪽을 '0'으로 채워 지정된 너비로 맞춤
s = "42"
print(s.zfill(5))  # 출력: 00042

기타 문자열 메서드

  1. str.isalnum()
  • 문자열이 알파벳 문자와 숫자로만 이루어져 있는지 확인
s = "hello123"
print(s.isalnum())  # 출력: True
  1. str.isalpha()
  • 문자열이 알파벳 문자로만 이루어져 있는지 확인
s = "hello"
print(s.isalpha())  # 출력: True
  1. str.isascii()
  • 문자열이 아스키 문자로만 이루어져 있는지 확인
s = "hello"
print(s.isascii())  # 출력: True
  1. str.isdecimal()
  • 문자열이 10진수 문자로만 이루어져 있는지 확인
s = "12345"
print(s.isdecimal())  # 출력: True
  1. str.isdigit()
  • 문자열이 숫자로만 이루어져 있는지 확인
s = "12345"
print(s.isdigit())  # 출력: True
  1. str.isidentifier()
  • 문자열이 유효한 파이썬 식별자인지 확인
s = "variable_name"
print(s.isidentifier())  # 출력: True
  1. str.islower()
  • 문자열이 소문자로만 이루어져 있는지 확인
s = "hello"
print(s.islower())  # 출력: True
  1. str.isnumeric()
  • 문자열이 숫자로만 이루어져 있는지 확인
s = "12345"
print(s.isnumeric())  # 출력: True
  1. str.isprintable()
  • 문자열이 인쇄 가능한 문자로만 이루어져 있는지 확인
s = "hello"
print(s.isprintable())
  1. str.isspace()
  • 하나 이상의 문자가 있고 모든 문자가 공백인지 확인
s = "    "
print(s.isspace()) 
  1. str.istitle()
  • 첫 문자만 대문자이고 나머지가 소문자이면 True를 리턴한다.
  • 문자열은 공백과 구분 문자를 포함할 수 있다.
  • 문자열이 인쇄 가능한 문자로만 이루어져 있는지 확인
s = "Hello World"
print(s.istitle())
  1. str.isupper()
  • 문자열이 모두 대분자인지 확인
s = "HELLO"
print(s.isupper()) 
반응형