한양과학기술고등학교

에듀테크 프로젝트 대시보드

문자열 메서드

split join strip replace find

모든 문자열 메서드는 원본을 바꾸지 않고 새 문자열을 반환합니다.

1. 대소문자 변환

"hello world".upper()       # => 'HELLO WORLD'
"HELLO".lower()             # => 'hello'
"hello world".title()      # => 'Hello World'
"hello".capitalize()       # => 'Hello'
"Hello".swapcase()         # => 'hELLO'
"Straße".casefold()        # => 'strasse'  (강한 소문자화 — 비교용)

2. 검색·판별

s = "banana"
s.find("na")        # => 2    (없으면 -1)
s.rfind("na")       # => 4    (오른쪽부터)
s.index("na")       # => 2    (없으면 ValueError)
s.count("a")        # => 3
s.startswith("ban") # => True
s.endswith(("x", "a"))  # => True  (튜플로 여러 개)

3. is* 판별 메서드

메서드True 조건
isdigit()모두 숫자 문자
isalpha()모두 글자
isalnum()모두 글자 또는 숫자
isspace()모두 공백
isupper()/islower()대문자/소문자 존재 & 전부 그 케이스
isidentifier()유효한 변수 이름

빈 문자열은 모두 False. 음수/소수점 판별에는 부족하므로 try: float(s) 사용.

4. 공백·접두접미 정리

"  hi  ".strip()            # => 'hi'
"  hi  ".rstrip()           # => '  hi'
"xxhixx".strip("x")        # => 'hi'   (제거할 문자 집합 지정)
"test.py".removesuffix(".py")   # => 'test'   (3.9+)
"__name".removeprefix("__")     # => 'name' 

5. 분리·결합

"a,b,c".split(",")          # => ['a', 'b', 'c']
"a b   c".split()           # => ['a', 'b', 'c']  (연속 공백 처리 + 양끝 제거)
"a,b,c".split(",", 1)       # => ['a', 'b,c']     (최대 분할 횟수)
"line1\nline2".splitlines()  # => ['line1', 'line2']
"key=value".partition("=")  # => ('key', '=', 'value')

"-".join(["2024", "01", "15"])   # => '2024-01-15' 

6. 치환·정렬

"aaa".replace("a", "b")        # => 'bbb'
"aaa".replace("a", "b", 1)     # => 'baa'
"42".zfill(5)                  # => '00042'
"hi".ljust(6, ".")            # => 'hi....'
"hi".center(6, "*")          # => '**hi**'

# 다중 문자 치환은 translate
table = str.maketrans({"a": "4", "e": "3"})
"apple tree".translate(table)  # => '4ppl3 tr33' 
"특별한 경우라도 규칙을 어길 만큼 특별하지는 않다"