포스트

[Python 100일 챌린지] Day 17 - 문자열 메서드 활용

[Python 100일 챌린지] Day 17 - 문자열 메서드 활용

문자열 다룰 때마다 for문 돌리고 if문 체크하느라 지치셨나요? 😰 Python이 이미 다 만들어놨습니다! 대소문자 변환, 공백 제거, 문자 검색… 실무에서 가장 자주 쓰이는 핵심 문자열 메서드 20개를 마스터해봅시다.

사용자 입력 검증, 데이터 정제, 텍스트 분석에 바로 써먹을 수 있는 실전 예제와 함께 배웁니다! (22분 완독 ⭐⭐)

🎯 오늘의 학습 목표

📚 사전 지식


🎯 학습 목표 1: 문자열 메서드가 무엇인지 이해하기

문자열 메서드란?

문자열 메서드 = 문자열 객체에 내장된 편리한 기능들

문자열은 단순한 텍스트가 아니라, 다양한 기능을 가진 객체입니다. Python은 문자열을 다루기 위한 40개 이상의 메서드를 기본 제공합니다.

1
2
3
text = "Hello World"
print(type(text))  # <class 'str'>
print(dir(text))   # 사용 가능한 모든 메서드 확인

메서드 사용법

기본 구조: 문자열.메서드명(인자)

1
2
3
4
5
6
7
8
9
10
text = "hello"

# 대소문자 변환
print(text.upper())  # HELLO

# 검색
print(text.find("l"))  # 2

# 대체
print(text.replace("h", "H"))  # Hello

원본 문자열은 변경되지 않음 (Immutable)

중요: 문자열은 불변(immutable) 객체입니다. 메서드는 항상 새로운 문자열을 반환합니다.

1
2
3
4
5
text = "hello"
result = text.upper()

print(text)    # hello (원본 그대로)
print(result)  # HELLO (새로운 문자열)

주요 메서드 카테고리

카테고리 메서드 용도
대소문자 upper(), lower(), capitalize(), title() 문자 케이스 변환
검색 find(), index(), count(), startswith(), endswith() 텍스트 탐색
판별 isdigit(), isalpha(), isalnum(), isspace() 문자열 타입 확인
변경 replace(), strip(), lstrip(), rstrip() 문자열 수정
분할/결합 split(), join() 문자열 분해/조립

🎯 학습 목표 2: 대소문자 변환 메서드 익히기

기본 변환 메서드

Python은 5가지 대소문자 변환 메서드를 제공합니다.

메서드 기능 예시
upper() 모두 대문자로 “hello” → “HELLO”
lower() 모두 소문자로 “HELLO” → “hello”
capitalize() 첫 글자만 대문자 “hello world” → “Hello world”
title() 각 단어의 첫 글자 대문자 “hello world” → “Hello World”
swapcase() 대소문자 반전 “Hello” → “hELLO”

upper() - 모두 대문자로

1
2
3
4
5
6
7
text = "hello world"
print(text.upper())  # HELLO WORLD

# 실전 활용: 대소문자 구분 없는 비교
user_input = "Yes"
if user_input.upper() == "YES":
    print("승인되었습니다")

lower() - 모두 소문자로

1
2
3
4
5
6
7
text = "HELLO WORLD"
print(text.lower())  # hello world

# 실전 활용: 이메일 정규화
email = "USER@EXAMPLE.COM"
normalized_email = email.lower()
print(normalized_email)  # user@example.com

capitalize() - 첫 글자만 대문자

1
2
3
4
5
text = "hello world"
print(text.capitalize())  # Hello world

sentence = "python is fun"
print(sentence.capitalize())  # Python is fun

title() - 각 단어의 첫 글자 대문자

1
2
3
4
5
6
text = "hello world"
print(text.title())  # Hello World

# 실전 활용: 이름 정규화
name = "john doe"
print(name.title())  # John Doe

swapcase() - 대소문자 반전

1
2
3
4
5
6
text = "Hello World"
print(text.swapcase())  # hELLO wORLD

# 특이한 사용 예
text = "PyThOn"
print(text.swapcase())  # pYtHoN

판별 메서드 (대소문자 확인)

대소문자 여부를 확인하는 메서드도 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
text1 = "HELLO"
text2 = "hello"
text3 = "Hello"

print(text1.isupper())  # True
print(text2.islower())  # True
print(text3.isupper())  # False
print(text3.islower())  # False

# 실전 활용: 비밀번호 강도 검사
password = "MyPassword123"
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
print(f"대문자 포함: {has_upper}")  # True
print(f"소문자 포함: {has_lower}")  # True

🎯 학습 목표 3: 검색/대체 메서드 익히기

검색 메서드 비교표

메서드 찾으면 못 찾으면 용도
find(sub) 위치 반환 (int) -1 반환 안전한 검색
index(sub) 위치 반환 (int) ValueError 발생 확실할 때만 사용
count(sub) 등장 횟수 (int) 0 반환 빈도 분석
startswith(prefix) True/False False 접두사 확인
endswith(suffix) True/False False 접미사 확인

find() - 안전한 검색

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
text = "Python is fun"

# 기본 사용
print(text.find("is"))      # 7
print(text.find("Java"))    # -1 (못 찾음)

# 시작 위치 지정
print(text.find("n"))       # 5 (첫 번째 n)
print(text.find("n", 6))    # 13 (6번 위치 이후의 n)

# 시작/끝 범위 지정
print(text.find("n", 0, 10))  # 5 (0~10 범위에서 검색)

# 실전 활용: 문자열 포함 여부 확인
if text.find("Python") != -1:
    print("Python이 포함되어 있습니다")

index() - 에러 발생 검색

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
text = "Python is fun"

# 찾으면 위치 반환
print(text.index("is"))  # 7

# 못 찾으면 ValueError
try:
    print(text.index("Java"))  # ValueError 발생!
except ValueError:
    print("찾을 수 없습니다")

# 실전 활용: 확실히 있을 때만 사용
email = "user@example.com"
at_position = email.index("@")  # @ 기호는 반드시 있음
domain = email[at_position + 1:]
print(domain)  # example.com

count() - 등장 횟수 세기

1
2
3
4
5
6
7
8
9
text = "banana"
print(text.count("a"))   # 3
print(text.count("na"))  # 2
print(text.count("x"))   # 0

# 실전 활용: 단어 빈도 분석
article = "Python is great. Python is easy. Python is fun."
python_count = article.count("Python")
print(f"Python이 {python_count}번 등장합니다")  # 3번

startswith() / endswith() - 시작/끝 확인

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
filename = "document.pdf"

# 시작 확인
print(filename.startswith("doc"))  # True
print(filename.startswith("img"))  # False

# 끝 확인
print(filename.endswith(".pdf"))  # True
print(filename.endswith(".txt"))  # False

# 여러 조건 동시 확인 (튜플 사용)
image_file = "photo.jpg"
is_image = image_file.endswith((".jpg", ".png", ".gif"))
print(is_image)  # True

# 실전 활용: 파일 필터링
files = ["report.pdf", "image.png", "script.py", "data.csv"]
python_files = [f for f in files if f.endswith(".py")]
print(python_files)  # ['script.py']

replace() - 문자열 대체

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
text = "Hello World"
print(text.replace("World", "Python"))  # Hello Python

# 횟수 지정
text = "a b a c a"
print(text.replace("a", "x"))      # x b x c x (모두)
print(text.replace("a", "x", 2))   # x b x c a (2번만)

# 실전 활용: 데이터 정제
raw_phone = "010-1234-5678"
clean_phone = raw_phone.replace("-", "")
print(clean_phone)  # 01012345678

# 연쇄 replace
text = "Hello, World!"
clean = text.replace(",", "").replace("!", "")
print(clean)  # Hello World

strip() / lstrip() / rstrip() - 공백 제거

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
text = "  hello  "

# 양쪽 공백 제거
print(f"'{text.strip()}'")   # 'hello'

# 왼쪽만
print(f"'{text.lstrip()}'")  # 'hello  '

# 오른쪽만
print(f"'{text.rstrip()}'")  # '  hello'

# 특정 문자 제거
text = "xxxhelloxxx"
print(text.strip("x"))  # hello

text = "...hello..."
print(text.strip("."))  # hello

# 실전 활용: 사용자 입력 정제
user_input = "  john@example.com  "
clean_input = user_input.strip()
print(clean_input)  # john@example.com

🎯 학습 목표 4: 분할/결합 메서드 익히기

split() - 문자열을 리스트로 분할

기본 구조: 문자열.split(구분자, 최대분할횟수)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 공백으로 분할 (기본값)
text = "apple banana grape"
words = text.split()
print(words)  # ['apple', 'banana', 'grape']

# 특정 구분자로 분할
text = "2024-03-17"
parts = text.split("-")
print(parts)  # ['2024', '03', '17']

# 분할 횟수 제한
text = "a:b:c:d"
print(text.split(":"))     # ['a', 'b', 'c', 'd']
print(text.split(":", 1))  # ['a', 'b:c:d'] (1번만)
print(text.split(":", 2))  # ['a', 'b', 'c:d'] (2번만)

split() 실전 활용 예제

CSV 파싱:

1
2
3
4
5
6
7
8
csv_line = "홍길동,25,서울,개발자"
fields = csv_line.split(",")
name, age, city, job = fields

print(f"이름: {name}")  # 홍길동
print(f"나이: {age}")   # 25
print(f"도시: {city}")  # 서울
print(f"직업: {job}")   # 개발자

경로 분할:

1
2
3
4
5
6
7
path = "/home/user/documents/file.txt"
parts = path.split("/")
print(parts)  # ['', 'home', 'user', 'documents', 'file.txt']

# 파일명 추출
filename = parts[-1]
print(filename)  # file.txt

태그 파싱:

1
2
3
tags = "python,javascript,java,c++"
tag_list = tags.split(",")
print(tag_list)  # ['python', 'javascript', 'java', 'c++']

join() - 리스트를 문자열로 결합

기본 구조: "구분자".join(리스트)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 공백으로 결합
words = ["apple", "banana", "grape"]
text = " ".join(words)
print(text)  # apple banana grape

# 다양한 구분자
print("-".join(words))   # apple-banana-grape
print(", ".join(words))  # apple, banana, grape
print("\n".join(words))  # 줄바꿈으로 결합

# 빈 문자열로 결합
letters = ["H", "e", "l", "l", "o"]
word = "".join(letters)
print(word)  # Hello

join() 실전 활용 예제

경로 결합:

1
2
3
path_parts = ["home", "user", "documents", "file.txt"]
path = "/".join(path_parts)
print(path)  # home/user/documents/file.txt

SQL 쿼리 생성:

1
2
3
4
columns = ["id", "name", "age", "city"]
sql = f"SELECT {', '.join(columns)} FROM users"
print(sql)
# SELECT id, name, age, city FROM users

태그 생성:

1
2
3
tags = ["python", "tutorial", "beginner"]
hashtags = "#" + " #".join(tags)
print(hashtags)  # #python #tutorial #beginner

분할과 결합의 조합

데이터 변환:

1
2
3
4
5
# 날짜 형식 변환: YYYY-MM-DD → YYYY/MM/DD
date = "2024-03-17"
parts = date.split("-")
new_date = "/".join(parts)
print(new_date)  # 2024/03/17

대소문자 변환과 조합:

1
2
3
4
5
sentence = "hello world python"
words = sentence.split()
capitalized = [word.capitalize() for word in words]
result = " ".join(capitalized)
print(result)  # Hello World Python

기타 유용한 메서드

center(), ljust(), rjust() - 정렬

1
2
3
4
5
6
7
8
9
10
text = "Python"

# 가운데 정렬 (총 20자)
print(text.center(20, "-"))  # -------Python-------

# 왼쪽 정렬
print(text.ljust(20, "-"))   # Python--------------

# 오른쪽 정렬
print(text.rjust(20, "-"))   # --------------Python

zfill() - 숫자 앞에 0 채우기

1
2
3
4
5
6
7
8
9
10
11
12
# 숫자를 문자열로 변환 후 0 채우기
num = "42"
print(num.zfill(5))  # 00042

# 파일 넘버링
for i in range(1, 11):
    filename = f"file_{str(i).zfill(3)}.txt"
    print(filename)
# file_001.txt
# file_002.txt
# ...
# file_010.txt

💡 실전 팁 & 주의사항

Tip 1: find()와 index() 선택하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
text = "Python is fun"

# ❌ 위험한 방법 (못 찾으면 에러)
pos = text.index("Java")  # ValueError 발생!

# ✅ 안전한 방법
pos = text.find("Java")
if pos != -1:
    print(f"찾음: {pos}")
else:
    print("못 찾음")

# ✅ 확실히 있을 때만 index() 사용
email = "user@example.com"
at_pos = email.index("@")  # @ 기호는 반드시 있음

Tip 2: split()과 maxsplit 활용

1
2
3
4
5
6
7
8
9
10
11
12
# maxsplit으로 분할 횟수 제한
url = "https://example.com/blog/2024/03/17"
protocol, rest = url.split("://", 1)
print(protocol)  # https
print(rest)      # example.com/blog/2024/03/17

# 빈 문자열 주의
text = "a::b::c"
print(text.split("::"))  # ['a', 'b', 'c']

text = "::a::b::"
print(text.split("::"))  # ['', 'a', 'b', ''] (빈 문자열 포함)

Tip 3: strip()은 양쪽만 제거

1
2
3
4
5
6
7
8
9
10
11
12
13
# ❌ 중간 공백은 제거 안 됨
text = "  hello  world  "
print(text.strip())  # "hello  world" (중간 공백 그대로)

# ✅ 모든 공백 제거하려면 replace() 사용
text = "  hello  world  "
clean = text.replace(" ", "")
print(clean)  # "helloworld"

# ✅ 또는 split()과 join() 조합
words = text.split()
clean = " ".join(words)
print(clean)  # "hello world" (공백 1개로 정규화)

Tip 4: 메서드 체이닝

1
2
3
4
5
6
7
8
9
# 여러 메서드를 연결해서 사용
text = "  HELLO WORLD  "
result = text.strip().lower().replace(" ", "_")
print(result)  # hello_world

# 실전 활용: URL 슬러그 생성
title = "  Python Tutorial: Day 17  "
slug = title.strip().lower().replace(" ", "-").replace(":", "")
print(slug)  # python-tutorial-day-17

Tip 5: join()은 문자열 메서드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ❌ 리스트 메서드가 아님
words = ["a", "b", "c"]
# result = words.join("-")  # AttributeError!

# ✅ 구분자 문자열의 메서드
result = "-".join(words)
print(result)  # a-b-c

# join()은 문자열만 결합 가능
numbers = [1, 2, 3]
# result = "-".join(numbers)  # TypeError!

# ✅ 문자열로 변환 후 결합
result = "-".join(str(n) for n in numbers)
print(result)  # 1-2-3

Tip 6: 판별 메서드 조합하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 비밀번호 강도 검사
def check_password_strength(password):
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    has_special = any(not c.isalnum() for c in password)
    is_long = len(password) >= 8

    if all([has_upper, has_lower, has_digit, has_special, is_long]):
        return "강함"
    elif sum([has_upper, has_lower, has_digit, has_special]) >= 3 and is_long:
        return "보통"
    else:
        return "약함"

print(check_password_strength("Pass123!"))  # 강함
print(check_password_strength("password"))  # 약함

🧪 연습 문제

문제 1: 사용자 이름 검증 시스템

과제: 사용자 이름이 유효한지 검증하는 프로그램을 작성하세요. 여러 문자열 메서드를 조합하여 다양한 조건을 검사합니다.

초기 데이터:

1
2
3
4
5
6
7
8
9
10
usernames = [
    "hong123",      # 유효
    "Kim_456",      # 유효
    "  lee789  ",   # 공백 포함
    "PARK!@#",      # 특수문자 포함
    "choi",         # 너무 짧음
    "jung_2024_ok", # 유효
    "1234numbers",  # 숫자로 시작
    "VeryLongUsername1234567890"  # 너무 김
]

요구사항:

  1. 사용자 이름 유효성 조건:
    • 길이: 5~15자
    • 영문자 또는 숫자만 허용 (언더스코어 _ 허용)
    • 숫자로 시작 불가
    • 앞뒤 공백 자동 제거
    • 대소문자 구분 없음 (모두 소문자로 변환)
  2. 각 사용자 이름에 대해 다음 정보 출력:
    • 원본 이름
    • 정규화된 이름 (앞뒤 공백 제거, 소문자 변환)
    • 유효성 여부와 구체적인 이유
  3. 문자열 메서드 활용:
    • strip(): 앞뒤 공백 제거
    • lower(): 소문자 변환
    • replace(): 특수문자 확인용
    • isalnum(), isdigit(): 문자 타입 판별
    • startswith(): 시작 문자 검사
💡 힌트
  • 앞뒤 공백 제거: username.strip()
  • 소문자 변환: username.lower()
  • 길이 확인: len(username)
  • 첫 글자가 숫자인지: username[0].isdigit()
  • 언더스코어 허용하려면: 언더스코어를 빈 문자열로 치환 후 isalnum() 검사
  • for 루프로 각 문자 검사
✅ 정답
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
usernames = [
    "hong123",      # 유효
    "Kim_456",      # 유효
    "  lee789  ",   # 공백 포함
    "PARK!@#",      # 특수문자 포함
    "choi",         # 너무 짧음
    "jung_2024_ok", # 유효
    "1234numbers",  # 숫자로 시작
    "VeryLongUsername1234567890"  # 너무 김
]

print("===== 사용자 이름 검증 시스템 =====\n")

for username in usernames:
    print(f"원본: '{username}'")

    # 1단계: 정규화 (앞뒤 공백 제거 + 소문자 변환)
    normalized = username.strip().lower()
    print(f"정규화: '{normalized}'")

    # 2단계: 유효성 검사
    is_valid = True
    reason = "유효함"

    # 길이 검사 (5~15자)
    if len(normalized) < 5:
        is_valid = False
        reason = "너무 짧음 (5자 이상 필요)"
    elif len(normalized) > 15:
        is_valid = False
        reason = "너무 김 (15자 이하 필요)"

    # 숫자로 시작하는지 검사
    elif normalized[0].isdigit():
        is_valid = False
        reason = "숫자로 시작 불가"

    # 영문자, 숫자, 언더스코어만 허용
    else:
        for char in normalized:
            if not (char.isalnum() or char == "_"):
                is_valid = False
                reason = f"허용되지 않는 문자 포함: '{char}'"
                break

    # 결과 출력
    status = "✅ 유효" if is_valid else "❌ 무효"
    print(f"결과: {status} - {reason}")
    print("-" * 50)

# 추가 테스트: 특정 이름 상세 검증
print("\n===== 상세 검증 예제 =====")
test_name = "  Hong_123  "
print(f"테스트 이름: '{test_name}'")

# 단계별 정규화
step1 = test_name.strip()
print(f"1. 공백 제거: '{step1}'")

step2 = step1.lower()
print(f"2. 소문자 변환: '{step2}'")

# 문자 분석
print(f"\n문자 분석:")
print(f"  - 길이: {len(step2)}")
print(f"  - 첫 글자: '{step2[0]}' (숫자: {step2[0].isdigit()})")
print(f"  - 마지막 글자: '{step2[-1]}'")

# 각 문자 타입 검사
print(f"  - 문자별 타입:")
for i, char in enumerate(step2):
    char_type = []
    if char.isalpha():
        char_type.append("영문")
    if char.isdigit():
        char_type.append("숫자")
    if char == "_":
        char_type.append("언더스코어")
    if not char.isalnum() and char != "_":
        char_type.append("특수문자")
    print(f"      {i}: '{char}' - {', '.join(char_type)}")

출력:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
===== 사용자 이름 검증 시스템 =====

원본: 'hong123'
정규화: 'hong123'
결과: ✅ 유효 - 유효함
--------------------------------------------------
원본: 'Kim_456'
정규화: 'kim_456'
결과: ✅ 유효 - 유효함
--------------------------------------------------
원본: '  lee789  '
정규화: 'lee789'
결과: ✅ 유효 - 유효함
--------------------------------------------------
원본: 'PARK!@#'
정규화: 'park!@#'
결과: ❌ 무효 - 허용되지 않는 문자 포함: '!'
--------------------------------------------------
원본: 'choi'
정규화: 'choi'
결과: ❌ 무효 - 너무 짧음 (5자 이상 필요)
--------------------------------------------------
원본: 'jung_2024_ok'
정규화: 'jung_2024_ok'
결과: ✅ 유효 - 유효함
--------------------------------------------------
원본: '1234numbers'
정규화: '1234numbers'
결과: ❌ 무효 - 숫자로 시작 불가
--------------------------------------------------
원본: 'VeryLongUsername1234567890'
정규화: 'verylongusername1234567890'
결과: ❌ 무효 - 너무 김 (15자 이하 필요)
--------------------------------------------------

===== 상세 검증 예제 =====
테스트 이름: '  Hong_123  '
1. 공백 제거: 'Hong_123'
2. 소문자 변환: 'hong_123'

문자 분석:
  - 길이: 8자
  - 첫 글자: 'h' (숫자: False)
  - 마지막 글자: '3'
  - 문자별 타입:
      0: 'h' - 영문
      1: 'o' - 영문
      2: 'n' - 영문
      3: 'g' - 영문
      4: '_' - 언더스코어
      5: '1' - 숫자
      6: '2' - 숫자
      7: '3' - 숫자

문제 2: 텍스트 데이터 분석 및 변환 시스템

과제: 여러 문장으로 이루어진 텍스트를 분석하고, 다양한 방식으로 변환하는 프로그램을 작성하세요.

초기 데이터:

1
2
3
4
text = """
Python is Easy. Python is Powerful. Python is Fun!
Learn Python today. Start your Python journey now.
"""

요구사항:

  1. 텍스트 기본 분석:
    • 전체 문자 수 (공백 포함/제외)
    • 단어 개수
    • 문장 개수
    • 특정 단어(“Python”) 출현 횟수 (대소문자 구분/비구분)
  2. 텍스트 변환:
    • 모든 문장 첫 글자 대문자로 변환
    • 공백을 언더스코어(_)로 변환
    • URL 슬러그 형식으로 변환 (소문자, 하이픈 구분)
    • 단어 리스트 추출 및 정렬
  3. 검색 기능:
    • 특정 단어의 첫 번째 위치
    • 특정 단어로 시작하는 문장 찾기
    • 특정 단어로 끝나는 문장 찾기
💡 힌트
  • 앞뒤 공백 제거: strip()
  • 문장 분리: split('.') 또는 split('!')
  • 단어 분리: split()
  • 대소문자 변환: upper(), lower(), title(), capitalize()
  • 특정 문자 개수: count()
  • 검색: find(), index(), startswith(), endswith()
  • 결합: join()
✅ 정답
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
text = """
Python is Easy. Python is Powerful. Python is Fun!
Learn Python today. Start your Python journey now.
"""

print("===== 텍스트 데이터 분석 =====")
print(f"원본 텍스트:\n{text}\n")

# 1단계: 텍스트 정규화
clean_text = text.strip()
print(f"정규화된 텍스트:\n{clean_text}\n")

# 2단계: 기본 분석
print("===== 기본 통계 =====")
print(f"전체 문자 수 (공백 포함): {len(clean_text)}")
print(f"전체 문자 수 (공백 제외): {len(clean_text.replace(' ', '').replace('\n', ''))}")

# 단어 개수
words = clean_text.split()
print(f"단어 개수: {len(words)}")

# 문장 개수 (마침표와 느낌표 기준)
sentences_dot = clean_text.split('.')
sentences_excl = clean_text.split('!')
sentence_count = len([s for s in sentences_dot if s.strip()]) + \
                 len([s for s in sentences_excl if s.strip() and '.' not in s]) - 1
print(f"문장 개수: {sentence_count}")

# Python 단어 출현 횟수
python_count = clean_text.count("Python")
python_count_lower = clean_text.lower().count("python")
print(f"'Python' 출현 횟수 (대소문자 구분): {python_count}")
print(f"'python' 출현 횟수 (대소문자 무시): {python_count_lower}")

# 3단계: 텍스트 변환
print("\n===== 텍스트 변환 =====")

# 모든 문장 첫 글자 대문자
title_text = clean_text.title()
print(f"1. Title Case:\n{title_text}\n")

# 공백을 언더스코어로
underscore_text = clean_text.replace(" ", "_").replace("\n", "_")
print(f"2. 공백 → 언더스코어:\n{underscore_text}\n")

# URL 슬러그 생성 (한 줄로 변환 + 소문자 + 특수문자 제거 + 하이픈)
single_line = clean_text.replace("\n", " ")
slug = single_line.strip().lower()
for char in "!?,.":
    slug = slug.replace(char, " ")
slug_words = slug.split()
slug_final = "-".join(slug_words)
print(f"3. URL 슬러그:\n{slug_final}\n")

# 4단계: 단어 리스트 추출 및 정렬
print("===== 단어 분석 =====")

# 특수문자 제거한 단어 리스트
clean_words = []
for word in words:
    # 특수문자 제거
    cleaned = word
    for char in "!?,.":
        cleaned = cleaned.replace(char, "")
    if cleaned:
        clean_words.append(cleaned.lower())

# 중복 제거 및 정렬
unique_words = list(set(clean_words))
unique_words.sort()

print(f"총 단어 수: {len(clean_words)}")
print(f"고유 단어 수: {len(unique_words)}")
print(f"고유 단어 목록 (정렬):\n{', '.join(unique_words)}")

# 5단계: 검색 기능
print("\n===== 검색 기능 =====")

# Python의 첫 번째 위치
first_pos = clean_text.find("Python")
print(f"'Python' 첫 번째 위치: {first_pos}")

# 모든 Python 위치 찾기
print(f"'Python' 모든 위치:")
start = 0
positions = []
while True:
    pos = clean_text.find("Python", start)
    if pos == -1:
        break
    positions.append(pos)
    start = pos + 1
print(f"  위치: {positions}")

# 문장별 분석
sentences = [s.strip() for s in clean_text.replace('!', '.').split('.') if s.strip()]
print(f"\n문장별 분석:")
for i, sentence in enumerate(sentences, 1):
    print(f"  문장 {i}: {sentence}")
    print(f"    - 'Python'으로 시작: {sentence.startswith('Python')}")
    print(f"    - 'now'로 끝남: {sentence.lower().endswith('now')}")

# 6단계: 단어 출현 빈도
print("\n===== 단어 출현 빈도 TOP 5 =====")
word_freq = {}
for word in clean_words:
    word_freq[word] = word_freq.get(word, 0) + 1

# 빈도순 정렬
sorted_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
for i, (word, count) in enumerate(sorted_freq[:5], 1):
    print(f"{i}. '{word}': {count}")

출력:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
===== 텍스트 데이터 분석 =====
원본 텍스트:

Python is Easy. Python is Powerful. Python is Fun!
Learn Python today. Start your Python journey now.


정규화된 텍스트:
Python is Easy. Python is Powerful. Python is Fun!
Learn Python today. Start your Python journey now.

===== 기본 통계 =====
전체 문자 수 (공백 포함): 103자
전체 문자 수 (공백 제외): 84자
단어 개수: 15개
문장 개수: 5개
'Python' 출현 횟수 (대소문자 구분): 5회
'python' 출현 횟수 (대소문자 무시): 5회

===== 텍스트 변환 =====
1. Title Case:
Python Is Easy. Python Is Powerful. Python Is Fun!
Learn Python Today. Start Your Python Journey Now.

2. 공백 → 언더스코어:
Python_is_Easy._Python_is_Powerful._Python_is_Fun!_Learn_Python_today._Start_your_Python_journey_now.

3. URL 슬러그:
python-is-easy-python-is-powerful-python-is-fun-learn-python-today-start-your-python-journey-now

===== 단어 분석 =====
총 단어 수: 15개
고유 단어 수: 11개
고유 단어 목록 (정렬):
easy, fun, is, journey, learn, now, powerful, python, start, today, your

===== 검색 기능 =====
'Python' 첫 번째 위치: 0
'Python' 모든 위치:
  위치: [0, 16, 40, 63, 81]

문장별 분석:
  문장 1: Python is Easy
    - 'Python'으로 시작: True
    - 'now'로 끝남: False
  문장 2: Python is Powerful
    - 'Python'으로 시작: True
    - 'now'로 끝남: False
  문장 3: Python is Fun
    - 'Python'으로 시작: True
    - 'now'로 끝남: False
  문장 4: Learn Python today
    - 'Python'으로 시작: False
    - 'now'로 끝남: False
  문장 5: Start your Python journey now
    - 'Python'으로 시작: False
    - 'now'로 끝남: True

===== 단어 출현 빈도 TOP 5 =====
1. 'python': 5회
2. 'is': 3회
3. 'easy': 1회
4. 'powerful': 1회
5. 'fun': 1회

🎯 연습 문제 핵심 포인트

문제 1에서 배운 것:

  • 메서드 체이닝: strip().lower()로 여러 변환 연결
  • 판별 메서드 조합: isalnum(), isdigit(), isalpha()
  • 문자열 순회: for char in string으로 각 문자 검사
  • 조건부 검증: 다양한 조건을 단계별로 검사
  • 정규화 패턴: 사용자 입력 처리의 실전 패턴

문제 2에서 배운 것:

  • 복합 텍스트 분석: 문자, 단어, 문장 수준의 다층 분석
  • 검색 메서드: find(), startswith(), endswith() 활용
  • 변환 메서드 조합: split() + join()으로 데이터 변환
  • 빈도 분석: 딕셔너리와 문자열 메서드 결합
  • 실전 패턴: URL 슬러그, 단어 추출, 통계 생성

📝 오늘 배운 내용 정리

  1. 문자열 메서드: 문자열 객체에 내장된 40개 이상의 편리한 기능
  2. 대소문자 변환: upper(), lower(), capitalize(), title(), swapcase()
  3. 검색 메서드: find(), index(), count(), startswith(), endswith()
  4. 변경 메서드: replace(), strip(), lstrip(), rstrip()
  5. 분할/결합: split()로 분해, join()으로 조립
  6. 판별 메서드: isdigit(), isalpha(), isalnum(), isupper(), islower()

🔗 관련 자료


📚 이전 학습

Day 16: 문자열 포맷팅 (f-string) ⭐⭐

어제는 f-string으로 문자열을 포맷팅하는 방법을 배웠습니다!

📚 다음 학습

Day 18: 리스트 컴프리헨션 ⭐⭐

내일은 리스트를 간결하게 생성하는 컴프리헨션 문법을 배웁니다!


“늦었다고 생각할 때가 가장 빠른 시기입니다!” 🚀

Day 17/100 Phase 2: 자료형 마스터하기 #100DaysOfPython
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.