여러분이 사용하고 계신 브라우저는 HTML5를 지원하지 않기 때문에 몇몇 요소가 제대로 보이도록 JScript를 사용하고 있습니다. 하지만 여러분의 브라우저 설정에서 스크립트 기능이 꺼져있으므로, 현재 페이지를 제대로 확인하시려면 스크립트 기능을 켜주셔야 합니다. Python - 문자열 메서드

Python – 문자열 메서드

2주전 작성

Python 문자열 메서드 종합 가이드

Python 문자열 메서드는 텍스트 처리와 데이터 조작을 위한 강력한 도구 모음이다. 문자열은 불변(immutable) 객체이므로 모든 메서드는 원본을 수정하지 않고 새로운 문자열을 반환한다. 이러한 메서드들을 적절히 활용하면 복잡한 텍스트 처리 작업을 간결하고 효율적으로 수행할 수 있다.

💡 핵심 개념:
• 문자열은 불변이므로 메서드 결과를 새 변수에 할당해야 한다
• 메서드 체이닝을 활용하여 여러 변환을 연속적으로 적용할 수 있다
• find 계열은 실패 시 -1을, index 계열은 예외를 발생시킨다
• 성능이 중요한 경우 적절한 메서드 선택이 필요하다

대소문자 변환 메서드

대소문자 변환 메서드는 텍스트 정규화와 대소문자를 구분하지 않는 비교에서 핵심적인 역할을 담당한다.

기본 변환 메서드

txt = "Hello World"
print(txt.upper())
print(txt.lower())
print(txt.capitalize())
print(txt.title())

위 코드는 “HELLO WORLD”, “hello world”, “Hello world”, “Hello World”를 각각 출력한다.

고급 변환 메서드

casefold() 메서드는 lower()보다 강력한 소문자 변환을 제공하며, 국제화된 텍스트 처리에서 중요하다.

german_text = "Straße"
print(german_text.lower())
print(german_text.casefold())
print("Hello World".swapcase())

위 코드는 “straße”, “strasse”, “hELLO wORLD”를 출력한다.

공백 처리 및 정렬 메서드

이 메서드들은 문자열의 공백을 제거하거나 지정된 폭에 맞춰 정렬하는 기능을 제공한다.

공백 제거

messy_text = "  --Hello World--  "
print(messy_text.strip())
print(messy_text.strip(" -"))
print(messy_text.lstrip(" -"))
print(messy_text.rstrip(" -"))

위 코드는 “–Hello World–“, “Hello World”, “Hello World– “, ” –Hello World”을 각각 출력한다.

정렬 및 패딩

text = "Python"
print(text.center(20, "*"))
print(text.ljust(20, "."))
print(text.rjust(20, "."))
print("42".zfill(8))

위 코드는 “*******Python*******”, “Python…………..”, “…………..Python”, “00000042”를 각각 출력한다.

검색 및 위치 메서드

문자열 내에서 특정 패턴을 찾거나 위치를 확인하는 메서드들이다.

위치 검색

text = "banana"
print(text.find("na"))
print(text.rfind("na"))
print(text.index("ba"))
print(text.count("a"))

위 코드는 2, 4, 0, 3을 각각 출력한다. find()는 찾지 못하면 -1을 반환하지만, index()는 ValueError 예외를 발생시킨다.

접두사 및 접미사 검사

filename = "document.pdf"
print(filename.startswith("doc"))
print(filename.endswith(".pdf"))
print(filename.startswith(("doc", "file")))
print(filename.endswith((".pdf", ".txt")))

위 코드는 모두 True를 출력한다. 튜플을 사용하여 여러 접두사나 접미사를 동시에 검사할 수 있다.

문자열 검증 메서드

문자열의 구성 요소나 형식을 확인하는 불린 값을 반환하는 메서드들이다.

문자 유형 검사

print("abc123".isalnum())
print("abc".isalpha())
print("123".isdigit())
print("123".isnumeric())
print("123".isdecimal())

위 코드는 모두 True를 출력한다. isdigit(), isnumeric(), isdecimal()은 서로 다른 범위의 숫자 문자를 검증한다.

대소문자 상태 검사

print("hello".islower())
print("HELLO".isupper())
print("Hello World".istitle())
print(" ".isspace())
print("valid_name".isidentifier())

위 코드는 모두 True를 출력한다.

분할 및 결합 메서드

문자열을 나누거나 여러 문자열을 결합하는 메서드들이다.

문자열 분할

data = "apple,banana,cherry,date"
print(data.split(","))
print(data.split(",", 2))
print(data.rsplit(",", 2))
print("line1\nline2\nline3".splitlines())

위 코드는 [‘apple’, ‘banana’, ‘cherry’, ‘date’], [‘apple’, ‘banana’, ‘cherry,date’], [‘apple,banana’, ‘cherry’, ‘date’], [‘line1’, ‘line2’, ‘line3’]을 각각 출력한다.

파티션 분할

url = "https://www.example.com/page"
print(url.partition("://"))
print(url.rpartition("/"))

위 코드는 (‘https’, ‘://’, ‘www.example.com/page’), (‘https://www.example.com’, ‘/’, ‘page’)를 각각 출력한다.

문자열 결합

words = ["Python", "is", "awesome"]
print(" ".join(words))
print("-".join(words))
print("".join(words))

위 코드는 “Python is awesome”, “Python-is-awesome”, “Pythonisawesome”을 각각 출력한다.

문자 변환 메서드

문자열의 내용을 변환하거나 특수 처리를 수행하는 메서드들이다.

문자 치환

text = "one one one two"
print(text.replace("one", "ONE"))
print(text.replace("one", "ONE", 2))

위 코드는 “ONE ONE ONE two”, “ONE ONE one two”를 각각 출력한다.

문자 매핑 변환

text = "2023-12-25"
translation_table = str.maketrans("-", "/")
print(text.translate(translation_table))

complex_table = str.maketrans({"a": "A", "e": "E", "i": "I"})
print("hello world".translate(complex_table))

위 코드는 “2023/12/25”, “hEllo world”를 각각 출력한다.

탭 확장 및 인코딩

tabbed_text = "Name\tAge\tCity"
print(tabbed_text.expandtabs(4))
print(tabbed_text.expandtabs(8))

korean_text = "안녕하세요"
encoded = korean_text.encode("utf-8")
print(type(encoded), len(encoded))

위 코드는 탭이 4칸과 8칸 공백으로 확장된 결과와 바이트 객체 정보를 출력한다.

문자열 메서드 종합 표

분류 메서드 기능 반환 타입 예시
대소문자 upper(), lower() 대소문자 변환 str “Hi”.upper() → “HI”
대소문자 casefold() 강력한 소문자 변환 str “Straße”.casefold() → “strasse”
대소문자 capitalize(), title() 첫 글자/각 단어 대문자화 str “hi world”.title() → “Hi World”
공백처리 strip(), lstrip(), rstrip() 양끝/왼쪽/오른쪽 공백 제거 str ” hi “.strip() → “hi”
정렬 center(), ljust(), rjust() 가운데/왼쪽/오른쪽 정렬 str “hi”.center(5, “*”) → “*hi**”
정렬 zfill() 앞쪽을 0으로 채움 str “42”.zfill(5) → “00042”
검색 find(), rfind() 부분 문자열 위치 (없으면 -1) int “hello”.find(“e”) → 1
검색 index(), rindex() 부분 문자열 위치 (없으면 예외) int “hello”.index(“e”) → 1
검색 count() 부분 문자열 개수 int “hello”.count(“l”) → 2
검증 startswith(), endswith() 접두사/접미사 확인 bool “hi.txt”.endswith(“.txt”) → True
검증 isalpha(), isdigit(), isalnum() 문자 유형 확인 bool “abc”.isalpha() → True
검증 islower(), isupper(), istitle() 대소문자 상태 확인 bool “HELLO”.isupper() → True
검증 isspace(), isidentifier() 공백/식별자 여부 확인 bool “var_1”.isidentifier() → True
분할 split(), rsplit() 구분자 기준 분할 list “a,b,c”.split(“,”) → [‘a’, ‘b’, ‘c’]
분할 partition(), rpartition() 구분자 기준 3분할 tuple “a=b”.partition(“=”) → (‘a’, ‘=’, ‘b’)
분할 splitlines() 줄바꿈 기준 분할 list “a\nb”.splitlines() → [‘a’, ‘b’]
결합 join() 시퀀스 요소 결합 str “,”.join([‘a’, ‘b’]) → “a,b”
변환 replace() 부분 문자열 교체 str “hi”.replace(“i”, “e”) → “he”
변환 translate() 문자 매핑 변환 str 변환 테이블 기반 치환
변환 expandtabs() 탭을 공백으로 확장 str “a\tb”.expandtabs(4) → “a b”
인코딩 encode() 바이트로 인코딩 bytes “안녕”.encode(“utf-8”)

실무 활용 예제

문자열 메서드들을 조합하여 실제 업무에서 자주 발생하는 텍스트 처리 작업을 수행하는 패턴을 살펴보자.

사용자 입력 검증

def validate_email(email):
email = email.strip().lower()

if not email or email.count("@") != 1:
return False, "올바른 이메일 형식이 아닙니다."

local, domain = email.split("@")

if not local or not domain:
return False, "이메일 주소가 불완전합니다."

if not domain.count(".") >= 1:
return False, "도메인 형식이 올바르지 않습니다."

return True, "유효한 이메일입니다."

print(validate_email(" User@Example.COM "))
print(validate_email("invalid.email"))

데이터 정제 파이프라인

def clean_text_data(text):
if not isinstance(text, str):
return ""

cleaned = text.strip()
cleaned = ' '.join(cleaned.split())
cleaned = cleaned.replace('\t', ' ')
cleaned = cleaned.title()

return cleaned

raw_data = [" john doe ", "\tJANE\tSMITH\t", " bob WILSON "]
cleaned_data = [clean_text_data(item) for item in raw_data]
print(cleaned_data)

텍스트 분석

def analyze_text(text):
text = text.strip()

analysis = {
'length': len(text),
'words': len(text.split()),
'lines': len(text.splitlines()),
'uppercase_ratio': sum(1 for c in text if c.isupper()) / len(text) if text else 0,
'digit_count': sum(1 for c in text if c.isdigit()),
'starts_with_capital': text and text[0].isupper(),
'ends_with_period': text.endswith('.')
}

return analysis

sample_text = """Hello World!
This is a sample text with 123 numbers.
It has multiple lines."""

print(analyze_text(sample_text))

💡 문자열 메서드 활용 모범 사례:
• 메서드 체이닝을 활용하되 가독성을 해치지 않도록 주의한다
• 사용자 입력은 항상 strip()으로 공백을 제거한 후 처리한다
• 대소문자 구분 없는 비교 시 casefold()를 사용한다
• 대량 문자열 결합 시 join()을 사용하여 성능을 확보한다
• find()와 index()의 차이를 이해하고 상황에 맞게 선택한다
• 검증 메서드를 조합하여 강력한 입력 검증 로직을 구성한다
• translate()를 활용하여 복잡한 문자 치환을 효율적으로 처리한다
• startswith()와 endswith()에서 튜플을 활용하여 다중 조건을 간결하게 처리한다

Python의 문자열 메서드는 텍스트 처리의 핵심 도구 모음이다. 각 메서드의 특성과 적절한 사용 시점을 이해하고 효과적으로 조합하면, 복잡한 텍스트 처리 작업을 간결하고 효율적으로 구현할 수 있다. 특히 메서드 체이닝과 적절한 검증 로직을 통해 견고하고 유지보수가 쉬운 텍스트 처리 파이프라인을 구축할 수 있다.

참고
Mingg`s Diary
밍구
공부 목적 블로그