# 여기에 코드를 작성하세요
text = "Python Programming"
Exercises: Chapter 6
Chapter 6: Strings - 연습문제
문제 1: 문자열 슬라이싱과 인덱싱
주어진 문자열 text = "Python Programming"에서 다음을 수행하는 코드를 작성하세요:
- 첫 번째 단어(“Python”)만 추출
- 마지막 단어(“Programming”)만 추출
- 문자열을 역순으로 만들기
- 2글자씩 건너뛰면서 추출 (“Pto rgamn”)
힌트: 슬라이싱의 start, stop, step 파라미터를 활용하세요.
문제 2: split과 join 활용
다음 작업을 수행하세요:
- 문자열
"apple,banana,cherry,date"를 쉼표로 분리하여 리스트로 만들기 - 리스트의 각 과일 이름을 대문자로 변환
- 변환된 리스트를 ” | “로 연결하여 새로운 문자열 생성
- 최종 결과 출력: “APPLE | BANANA | CHERRY | DATE”
힌트: split(), join(), upper() 메서드를 활용하세요.
# 여기에 코드를 작성하세요
fruits = "apple,banana,cherry,date"
문제 3: 문자열 공백 제거와 정리
다음 지저분한 사용자 입력을 정리하세요:
user_inputs = [
" hello@example.com ",
"\tuser@domain.com\n",
" admin@site.org\t\n",
"contact@company.com "
]각 이메일 주소에서:
- 앞뒤 공백 제거
- 모두 소문자로 변환
- 정리된 이메일을 리스트로 출력
힌트: strip(), lower() 메서드를 사용하세요.
# 여기에 코드를 작성하세요
user_inputs = [
" hello@example.com ",
"\tuser@domain.com\n",
" admin@site.org\t\n",
"contact@company.com "
]
문제 4: 문자열 검색과 카운팅
다음 텍스트에서:
text = "Python is powerful. Python is easy. Python is versatile. I love Python!"다음을 수행하세요:
- “Python”이 몇 번 등장하는지 카운트
- 첫 번째 “Python”의 위치 찾기
- 마지막 “Python”의 위치 찾기
- 텍스트가 “Python”으로 시작하는지 확인
- 텍스트가 느낌표로 끝나는지 확인
힌트: count(), find(), rfind(), startswith(), endswith() 메서드를 사용하세요.
# 여기에 코드를 작성하세요
text = "Python is powerful. Python is easy. Python is versatile. I love Python!"
문제 5: 문자열 치환과 변환
주어진 로그 메시지에서:
log = "ERROR: Failed to connect to database. ERROR: Connection timeout."다음을 수행하세요:
- 모든 “ERROR”를 “WARNING”으로 변경
- 첫 번째 “ERROR”만 “INFO”로 변경 (원본 문자열 사용)
- 문자열의 모든 마침표를 느낌표로 변경
힌트: replace() 메서드의 count 파라미터를 활용하세요.
# 여기에 코드를 작성하세요
log = "ERROR: Failed to connect to database. ERROR: Connection timeout."
문제 6: f-string 포매팅
다음 학생 정보를 사용하여 보기 좋게 포맷된 리포트를 출력하세요:
name = "Alice"
student_id = 12345
gpa = 3.87654
courses = ["Python", "Data Science", "Machine Learning"]요구사항:
- 이름은 20자 폭으로 왼쪽 정렬
- 학번은 10자 폭으로 오른쪽 정렬, 0으로 채우기
- GPA는 소수점 둘째 자리까지 표시
- 수강 과목은 쉼표로 구분하여 표시
출력 예시:
학생 이름: Alice
학 번: 0000012345
G P A : 3.88
수강 과목: Python, Data Science, Machine Learning
# 여기에 코드를 작성하세요
name = "Alice"
student_id = 12345
gpa = 3.87654
courses = ["Python", "Data Science", "Machine Learning"]
문제 7: 문자열 검증 메서드
다음 문자열들을 분석하여 각각의 특성을 확인하세요:
strings = ["12345", "Python3", "hello", "WORLD", "Hello World", ""]각 문자열에 대해 다음을 확인하고 결과를 출력하세요:
- 모두 숫자로만 구성되어 있는지 (isdigit)
- 모두 알파벳으로만 구성되어 있는지 (isalpha)
- 모두 소문자인지 (islower)
- 모두 대문자인지 (isupper)
- 알파벳과 숫자로만 구성되어 있는지 (isalnum)
출력 형식:
"12345": digit=True, alpha=False, lower=False, upper=False, alnum=True
...
# 여기에 코드를 작성하세요
strings = ["12345", "Python3", "hello", "WORLD", "Hello World", ""]
문제 8: 이스케이프 시퀀스와 특수 문자
다음 작업을 수행하세요:
탭으로 구분된 3열 테이블을 생성하고 출력
- 헤더: “Name”, “Age”, “City”
- 데이터: (“Alice”, 25, “Seoul”), (“Bob”, 30, “Busan”)
파일 경로를 나타내는 문자열 생성:
C:\Users\Python\Documents다음 텍스트를 3줄로 출력:
Python은 "간결하고" 강력합니다. Python은 '배우기' 쉽습니다. Python은 \n과 \t 같은 이스케이프 시퀀스를 지원합니다.
힌트: 이스케이프 시퀀스 \t, \n, \\, \", \'를 활용하세요.
# 여기에 코드를 작성하세요
문제 9: 문자열과 리스트 상호 변환
- 주어진 문자열
sentence = "The quick brown fox"에서:
- 문자열을 문자 리스트로 변환
- 리스트의 모든 공백을 하이픈(‘-’)으로 변경
- 리스트를 다시 문자열로 변환
- 결과 출력: “The-quick-brown-fox”
- 위 작업을 리스트로 변환 없이 문자열 메서드만으로 수행해보세요.
힌트: list(), join() 함수와 replace() 메서드를 활용하세요.
# 여기에 코드를 작성하세요
sentence = "The quick brown fox"
문제 10: URL 파싱하기
다음 URL에서 정보를 추출하세요:
url = "https://www.example.com:8080/path/to/page?name=John&age=30#section"추출할 정보: 1. 프로토콜 (https) 2. 도메인 (www.example.com) 3. 포트 (8080) 4. 경로 (/path/to/page) 5. 쿼리 파라미터(물음표(?)이후 헤시(#)이전까지의 문자열)를 딕셔너리로 변환 {‘name’: ‘John’, ‘age’: ‘30’} 6. 프래그먼트 (section)
힌트: split(), find(), 슬라이싱을 조합하여 사용하세요. 각 구분자(://, :, /, ?, &, =, #)를 이용하세요.
# 여기에 코드를 작성하세요
url = "https://www.example.com:8080/path/to/page?name=John&age=30#section"
문제 11**: 텍스트 정규화 및 분석
주어진 텍스트를 정규화하고 단어 통계를 분석하세요.
text = """
Python is a HIGH-LEVEL programming language. Python's design philosophy emphasizes
code readability. Python is dynamically typed and garbage-collected. Python supports
multiple programming paradigms, including structured, object-oriented and functional
programming. Python is often described as a "batteries included" language.
"""요구사항:
- 모든 텍스트를 소문자로 변환
- 구두점(마침표, 쉼표, 따옴표 등)을 제거
- 단어를 추출하여 리스트로 저장
- 다음 통계를 계산하고 출력:
- 총 단어 수
- 고유 단어 수
- 가장 긴 단어와 그 길이
- 5글자 이상인 단어의 개수
- “python”이 등장하는 횟수
출력 예시:
총 단어 수: 45
고유 단어 수: 35
가장 긴 단어: programming (11글자)
5글자 이상 단어: 28개
"python" 등장 횟수: 5회
def analyze_text(text):
"""
텍스트를 정규화하고 통계를 분석합니다.
Args:
text: 분석할 텍스트
Returns:
dict: 통계 정보를 담은 딕셔너리
"""
import string
# 1. 소문자로 변환
text_lower = text.lower()
# 2. 구두점 제거 (힌트: str.maketrans와 translate 사용)
translator = str.maketrans('', '', string.punctuation)
text_clean = ...
# 3. 단어 추출
words = ...
# 4. 통계 계산
total_words = ...
unique_words = ... # 힌트: set() 사용
longest_word = ... # 힌트: max()와 key=len 사용
long_words = ... # 힌트: 리스트 컴프리헨션 사용
python_count = ... # 힌트: count() 메서드 사용
# 결과 출력
print(f"총 단어 수: {total_words}")
print(f"고유 단어 수: {unique_words}")
print(f"가장 긴 단어: {longest_word} ({len(longest_word)}글자)")
print(f"5글자 이상 단어: {long_words}개")
print(f'"python" 등장 횟수: {python_count}회')
return {
'total': total_words,
'unique': unique_words,
'longest': longest_word,
'long_count': long_words,
'python_count': python_count
}
# 테스트
text = """
Python is a HIGH-LEVEL programming language. Python's design philosophy emphasizes
code readability. Python is dynamically typed and garbage-collected. Python supports
multiple programming paradigms, including structured, object-oriented and functional
programming. Python is often described as a "batteries included" language.
"""
analyze_text(text)문제 12**: 스마트 문자열 포매터 구현
템플릿 문자열과 데이터 딕셔너리를 받아서 포맷팅된 문자열을 생성하는 함수를 작성하세요.
요구사항:
- 템플릿에서
{변수명}형태의 플레이스홀더를 찾기 - 플레이스홀더를 데이터 딕셔너리의 값으로 치환
- 포맷 옵션 지원:
{변수명:upper}- 대문자로 변환{변수명:lower}- 소문자로 변환{변수명:title}- 제목 케이스로 변환{변수명:len}- 문자열 길이 출력
- 데이터에 없는 변수는
[MISSING]으로 표시
예시:
template = "Hello, {name:upper}! You have {count} new messages. Status: {status:title}"
data = {"name": "alice", "count": 5, "status": "active"}
result = smart_format(template, data)
# "Hello, ALICE! You have 5 new messages. Status: Active"def smart_format(template, data):
"""
템플릿 문자열을 데이터로 포맷팅합니다.
Args:
template: 플레이스홀더를 포함한 템플릿 문자열
data: 치환할 데이터를 담은 딕셔너리
Returns:
str: 포맷팅된 문자열
"""
result = template
# 힌트 1: 중괄호 사이의 내용을 찾기 위한 반복문
# while "{" in result and "}" in result:
# start = result.find("{")
# end = result.find("}")
# ...
while "{" in result and "}" in result:
# 플레이스홀더 찾기
start = result.find("{")
end = result.find("}")
if start == -1 or end == -1 or start > end:
break
# 플레이스홀더 내용 추출
placeholder = result[start+1:end]
# 변수명과 포맷 옵션 분리
if ":" in placeholder:
var_name, format_opt = ... # 힌트: split(':') 사용
else:
var_name = placeholder
format_opt = None
# 데이터에서 값 가져오기
if var_name in data:
value = str(data[var_name])
# 포맷 옵션 적용
if format_opt == "upper":
value = ...
elif format_opt == "lower":
value = ...
elif format_opt == "title":
value = ...
elif format_opt == "len":
value = ...
else:
value = "[MISSING]"
# 치환
result = result[:start] + value + result[end+1:]
return result
# 테스트 케이스
print("=== 테스트 1 ===")
template1 = "Hello, {name:upper}! You have {count} new messages."
data1 = {"name": "alice", "count": 5}
print(smart_format(template1, data1))
# 예상 출력: "Hello, ALICE! You have 5 new messages."
print("\n=== 테스트 2 ===")
template2 = "User: {username:title}, Email length: {email:len}, Status: {status:upper}"
data2 = {"username": "john doe", "email": "john@example.com", "status": "active"}
print(smart_format(template2, data2))
# 예상 출력: "User: John Doe, Email length: 17, Status: ACTIVE"
print("\n=== 테스트 3 (누락된 데이터) ===")
template3 = "Name: {name}, Age: {age}, City: {city}"
data3 = {"name": "Bob", "age": 30}
print(smart_format(template3, data3))
# 예상 출력: "Name: Bob, Age: 30, City: [MISSING]"