Python 3.12+ 에서는 같은 인용부호 중첩, 백슬래시, 멀티라인이 허용되었다(PEP 701).
문자열 메서드 핵심
메서드
동작
예시
.upper() / .lower()
대/소문자 변환
"abc".upper() == "ABC"
.strip([chars])
양끝 공백/문자 제거
" x ".strip() == "x"
.lstrip() / .rstrip()
왼쪽/오른쪽만
.split(sep)
분할 → 리스트
"a,b,c".split(",") == ["a", "b", "c"]
.join(iterable)
결합
",".join(["a", "b"]) == "a,b"
.replace(old, new)
치환
"aaa".replace("a", "b") == "bbb"
.startswith() / .endswith()
접두/접미 검사
.find(sub) / .index(sub)
위치, -1 / 예외
.count(sub)
출현 횟수
.isdigit() / .isalpha() / .isspace()
문자 종류
.title() / .capitalize() / .swapcase()
케이스 변환
.zfill(n)
0 패딩
"7".zfill(3) == "007"
.format(*args, **kwargs)
구식 포매팅
python
s = "Hello, World"print(s.lower())print(s.replace("World", "Python"))print(s.split(", "))print("-".join(["a", "b", "c"]))print(s.find("World"))
결과
hello, worldHello, Python['Hello', 'World']a-b-c7
슬라이싱과 인덱싱
문자열은 시퀀스라서 정수 인덱스와 슬라이스가 가능하다.
python
s = "Python"print(s[0])print(s[-1])print(s[1:4])print(s[::-1]) # 뒤집기print(s[::2]) # 2칸씩
결과
PnythnohtyPPto
불변성과 연결 성능
# BAD: 매번 새 객체 생성, O(n^2)result = ""for s in many_strings: result += s# GOOD: join, O(n)result = "".join(many_strings)# 또는 io.StringIOfrom io import StringIObuf = StringIO()for s in many_strings: buf.write(s)result = buf.getvalue()
CPython 구현 최적화로 += 누적도 빠를 수 있지만 보장되지 않는다. join 사용이 정석.
인코딩
str는 유니코드 추상이고, 실제 바이트는 bytes다.
python
s = "안녕"b = s.encode("utf-8")print(b)print(len(s), "chars,", len(b), "bytes")# 다시 str로print(b.decode("utf-8"))
💬 댓글