PYTHON · 기초 문법
문자열 메서드
자주 쓰이는 문자열 메서드를 정리합니다. str은 불변(immutable)이므로 항상 새 문자열을 반환합니다.
기초 문법입문string문자열stripsplitjoin
핵심 설명
자주 쓰이는 문자열 메서드를 정리합니다. str은 불변(immutable)이므로 항상 새 문자열을 반환합니다.
Python code
text = " Hello, Python World! "
# 공백 제거
print(text.strip()) # "Hello, Python World!"
print(text.lstrip()) # "Hello, Python World! "
# 검색
print(text.find("Python")) # 9 (인덱스)
print(text.count("l")) # 3
print("Python" in text) # True
# 변환
print(text.strip().upper()) # "HELLO, PYTHON WORLD!"
print(text.strip().title()) # "Hello, Python World!"
print(text.strip().replace("World", "세계"))
# 분할과 결합
words = "a,b,c,d".split(",")
print(words) # ['a', 'b', 'c', 'd']
print("-".join(words)) # "a-b-c-d"
# 판별 메서드
print("12345".isdigit()) # True
print("hello".isalpha()) # True학습 팁
str.removeprefix()와 str.removesuffix()는 Python 3.9+에서 사용 가능한 편리한 메서드입니다.
주의할 점
str.replace()는 원본을 변경하지 않고 새 문자열을 반환합니다. 결과를 변수에 재할당해야 합니다.
자주 묻는 질문
문자열 메서드란 무엇인가요?
자주 쓰이는 문자열 메서드를 정리합니다. str 은 불변(immutable)이므로 항상 새 문자열을 반환합니다.
문자열 메서드 학습 시 주의할 점은 무엇인가요?
str.replace() 는 원본을 변경하지 않고 새 문자열을 반환합니다. 결과를 변수에 재할당해야 합니다.