1. strip()
문자열.strip()
양쪽 공백과 줄바꿈 제거
# 성공: 양쪽 공백을 모두 제거
text = " hello "
result = text.strip()
print(result)
# hello
# 성공: 양쪽 줄바꿈을 모두 제거
text = "\\nhello\\n"
print(text.strip())
# hello
# 주의: 원본 문자열은 변경되지 않음
text = " hello "
text.strip()
print(text)
# hello
text = text.strip()
print(text)
# hello
2. replace()
문자열.replace(기존값, 변경값)
문자열 치환
# 성공: 문자열 변경
text = "apple banana"
result = text.replace("banana", "orange")
print(result) # apple orange
# 성공: 여러 문자 변경 가능
text = "aaaa"
print(text.replace("a", "b")) # bbbb
# 주의: 원본 문자열은 변경되지 않음
text = "apple banana"
text.replace("banana", "orange")
print(text)
# apple banana
# 주의: 변경할 문자열이 없으면 그대로 반환
text = "apple banana"
print(text.replace("grape", "orange"))
# apple banana
3. split()
문자열.split(기준값)
문자열 나누기
# 성공: 쉼표 기준 분리
text = "a,b,c"
result = text.split(",")
print(result) # ['a', 'b', 'c']
# 성공: 공백 기준 분리
text = "python java c"
print(text.split()) # ['python', 'java', 'c']
# 주의: 결과는 리스트 타입
text = "a,b,c"
result = text.split(",")
print(type(result)) # <class 'list'>
# 주의: 기준값이 없으면 전체 문자열 반환
text = "abc"
print(text.split(",")) # ['abc']
4. join()
구분자.join(리스트)
리스트를 문자열로 합치기
# 성공: 쉼표로 문자열 연결
data= ["a","b","c"]
result=",".join(data)
print(result) # a,b,c
# 성공: 공백으로 문자열 연결
data= ["python","java","c"]
print(" ".join(data)) # python java c
# 주의: 리스트 내부는 문자열이어야 함
data= ["a",1,"c"]
",".join(data) # TypeError
# 해결 방법: 숫자는 문자열로 변환
data= ["a",str(1),"c"]
print(",".join(data)) # a,1,c
5. startswith()
문자열.startswith(값)
특정 문자열로 시작하는지 확인
# 성공: 문자열 시작 여부 확인
text="python"
print(text.startswith("py")) # True
print(text.startswith("java")) # False
# 주의: 대소문자를 구분함
text="Python"
print(text.startswith("py")) # False
6. endswith()
문자열.endswith(값)
특정 문자열로 끝나는지 확인
# 성공: 문자열 끝 여부 확인
text="image.png"
print(text.endswith(".png")) # True
print(text.endswith(".jpg")) # False
# 주의: 정확히 끝나야 함
text="image.png.backup"
print(text.endswith(".png")) # False
7. find()
문자열.find(찾을값)
문자열에서 특정 값의 위치(인덱스) 찾기
# 성공: 찾는 문자열의 시작 위치 반환
text = "hello python"
result = text.find("python")
print(result) # 6
# 성공: 첫 번째로 찾은 위치 반환
text = "banana"
print(text.find("a")) # 1
# 주의: 찾는 값이 없으면 -1 반환
text = "hello python"
print(text.find("java")) # -1
8. index()
문자열.index(찾을값)
문자열에서 특정 값의 위치(인덱스) 찾기
# 성공: 찾는 문자열의 시작 위치 반환
text = "hello python"
result = text.index("python")
print(result) # 6
# 성공: 첫 번째로 찾은 위치 반환
text = "banana"
print(text.index("a")) # 1
# 주의: 찾는 값이 없으면 에러 발생
text = "hello python"
print(text.index("java")) # ValueError
9. count()
문자열.count(찾을값)
문자열에서 특정 값의 개수 세기
# 성공: 특정 문자의 개수 반환
text = "banana"
result = text.count("a")
print(result) # 3
# 성공: 특정 문자열의 개수 반환
text = "hello hello python"
print(text.count("hello")) # 2
# 주의: 찾는 값이 없으면 0 반환
text = "banana"
print(text.count("z")) # 0
10. upper()
문자열.upper()
문자열을 대문자로 변경
# 성공: 소문자를 대문자로 변경
text = "hello"
result = text.upper()
print(result) # HELLO
# 성공: 이미 대문자인 문자는 그대로 유지
text = "Hello Python"
print(text.upper()) # HELLO PYTHON
# 주의: 원본 문자열은 변경되지 않음
text = "hello"
text.upper()
print(text) # hello
11. lower()
문자열.lower()
문자열을 소문자로 변경
# 성공: 대문자를 소문자로 변경
text = "HELLO"
result = text.lower()
print(result) # hello
# 성공: 섞여 있어도 모두 소문자로 변경
text = "Hello Python"
print(text.lower()) # hello python
# 주의: 원본 문자열은 변경되지 않음
text = "HELLO"
text.lower()
print(text) # HELLO
12. capitalize()
문자열.capitalize()
첫 글자는 대문자, 나머지는 소문자로 변경
# 성공: 첫 글자만 대문자로 변경
text = "hello"
result = text.capitalize()
print(result) # Hello
# 성공: 나머지 글자는 소문자로 변경
text = "hELLO PYTHON"
print(text.capitalize()) # Hello python
# 주의: 단어마다 첫 글자를 바꾸는 기능은 아님
text = "hello python"
print(text.capitalize()) # Hello python
13. title()
문자열.title()
각 단어의 첫 글자를 대문자로 변경
# 성공: 각 단어의 첫 글자 대문자
text = "hello python"
result = text.title()
print(result) # Hello Python
# 성공: 여러 단어도 적용
text = "i like python"
print(text.title()) # I Like Python
# 주의: 원본 문자열은 변경되지 않음
text = "hello python"
text.title()
print(text) # hello python
14. isdigit()
문자열.isdigit()
문자열이 숫자로만 구성되어 있는지 확인
# 성공: 숫자로만 구성된 경우
text = "12345"
result = text.isdigit()
print(result) # True
# 성공: 문자가 섞이면 False
text = "123a"
print(text.isdigit()) # False
# 주의: 공백이 있어도 False
text = "123 "
print(text.isdigit()) # False
# 주의: 음수 기호도 숫자가 아님
text = "-123"
print(text.isdigit()) # False
15. isalpha()
문자열.isalpha()
문자열이 문자로만 구성되어 있는지 확인
# 성공: 문자로만 구성된 경우
text = "python"
result = text.isalpha()
print(result) # True
# 성공: 숫자가 섞이면 False
text = "python3"
print(text.isalpha()) # False
# 주의: 공백이 있어도 False
text = "hello python"
print(text.isalpha()) # False
16. isalnum()
문자열.isalnum()
문자열이 문자 또는 숫자로만 구성되어 있는지 확인
# 성공: 문자와 숫자로 구성된 경우
text = "python3"
result = text.isalnum()
print(result) # True
# 성공: 문자만 있어도 True
text = "python"
print(text.isalnum()) # True
# 주의: 공백이나 특수문자가 있으면 False
text = "python 3"
print(text.isalnum()) # False
text = "python!"
print(text.isalnum()) # False
17. isspace()
문자열.isspace()
문자열이 공백 문자로만 구성되어 있는지 확인
# 성공: 공백만 있는 경우
text = " "
result = text.isspace()
print(result) # True
# 성공: 줄바꿈도 공백 문자로 판단
text = "\\\\n\\\\t"
print(text.isspace()) # True
# 주의: 일반 문자가 섞이면 False
text = " a "
print(text.isspace()) # False
# 주의: 빈 문자열은 False
text = ""
print(text.isspace()) # False
18. startswith()
문자열.startswith(시작값)
문자열이 특정 값으로 시작하는지 확인
# 성공: 특정 문자열로 시작하면 True
text = "python.txt"
result = text.startswith("python")
print(result) # True
# 성공: 특정 문자열로 시작하지 않으면 False
text = "python.txt"
print(text.startswith("java")) # False
# 주의: 대소문자를 구분함
text = "Python.txt"
print(text.startswith("python")) # False
19. endswith()
문자열.endswith(끝값)
문자열이 특정 값으로 끝나는지 확인
# 성공: 특정 문자열로 끝나면 True
text = "image.png"
result = text.endswith(".png")
print(result) # True
# 성공: 특정 문자열로 끝나지 않으면 False
text = "image.png"
print(text.endswith(".jpg")) # False
# 주의: 정확히 끝나는 값만 True
text = "image.png.backup"
print(text.endswith(".png")) # False
20. lstrip()
문자열.lstrip()
왼쪽 공백과 줄바꿈 제거
# 성공: 왼쪽 공백 제거
text = " hello "
result = text.lstrip()
print(result) # hello
# 성공: 왼쪽 줄바꿈 제거
text = "\\\\nhello\\\\n"
print(text.lstrip()) # hello
# 주의: 오른쪽 공백은 제거되지 않음
text = " hello "
print(text.lstrip()) # hello
# 주의: 원본 문자열은 변경되지 않음
text = " hello "
text.lstrip()
print(text) # hello
21. rstrip()
문자열.rstrip()
오른쪽 공백과 줄바꿈 제거
# 성공: 오른쪽 공백 제거
text = " hello "
result = text.rstrip()
print(result) # hello
# 성공: 오른쪽 줄바꿈 제거
text = "\\\\nhello\\\\n"
print(text.rstrip()) #
hello
# 주의: 왼쪽 공백은 제거되지 않음
text = " hello "
print(text.rstrip()) # hello
# 주의: 원본 문자열은 변경되지 않음
text = " hello "
text.rstrip()
print(text) # hello
22. zfill()
문자열.zfill(전체길이)
문자열 왼쪽을 0으로 채워 전체 길이 맞추기
# 성공: 전체 길이가 5가 되도록 0 채우기
text = "42"
result = text.zfill(5)
print(result) # 00042
# 성공: 이미 길이가 충분하면 그대로 반환
text = "12345"
print(text.zfill(5)) # 12345
# 주의: 전체 길이는 최종 문자열 길이 기준
text = "42"
print(text.zfill(3)) # 042
# 주의: 숫자가 아니라 문자열 메서드
num = 42
print(num.zfill(5)) # AttributeError
23. center()
문자열.center(전체길이)
문자열을 가운데 정렬하고 양쪽을 공백으로 채우기
# 성공: 전체 길이 10 기준 가운데 정렬
text = "hi"
result = text.center(10)
print(result) # hi
# 성공: 채울 문자 지정 가능
text = "hi"
print(text.center(10, "-")) # ----hi----
# 주의: 전체 길이가 문자열보다 작으면 그대로 반환
text = "hello"
print(text.center(3)) # hello
# 주의: 채울 문자는 한 글자만 가능
text = "hi"
print(text.center(10, "--")) # TypeError
24. ljust()
문자열.ljust(전체길이)
문자열을 왼쪽 정렬하고 오른쪽을 공백으로 채우기
# 성공: 전체 길이 10 기준 왼쪽 정렬
text = "hi"
result = text.ljust(10)
print(result) # hi
# 성공: 채울 문자 지정 가능
text = "hi"
print(text.ljust(10, "-")) # hi--------
# 주의: 전체 길이가 문자열보다 작으면 그대로 반환
text = "hello"
print(text.ljust(3)) # hello
# 주의: 채울 문자는 한 글자만 가능
text = "hi"
print(text.ljust(10, "--")) # TypeError
25. rjust()
문자열.rjust(전체길이)
문자열을 오른쪽 정렬하고 왼쪽을 공백으로 채우기
# 성공: 전체 길이 10 기준 오른쪽 정렬
text = "hi"
result = text.rjust(10)
print(result) # hi
# 성공: 채울 문자 지정 가능
text = "hi"
print(text.rjust(10, "-")) # --------hi
# 주의: 전체 길이가 문자열보다 작으면 그대로 반환
text = "hello"
print(text.rjust(3)) # hello
# 주의: 채울 문자는 한 글자만 가능
text = "hi"
print(text.rjust(10, "--")) # TypeError
26. partition()
문자열.partition(기준값)
기준값을 기준으로 문자열을 3개로 나누기
# 성공: 기준값 앞, 기준값, 기준값 뒤로 분리
text = "hello-python"
result = text.partition("-")
print(result) # ('hello', '-', 'python')
# 성공: 결과는 튜플
text = "name=kim"
print(text.partition("=")) # ('name', '=', 'kim')
# 주의: 기준값이 없으면 원본, 빈 문자열, 빈 문자열 반환
text = "hello-python"
print(text.partition("/")) # ('hello-python', '', '')
27. rpartition()
문자열.rpartition(기준값)
오른쪽에서부터 기준값을 찾아 문자열을 3개로 나누기
# 성공: 마지막 기준값을 기준으로 분리
text = "2026-05-28"
result = text.rpartition("-")
print(result) # ('2026-05', '-', '28')
# 성공: 파일 경로 분리 등에 사용 가능
text = "folder/sub/file.txt"
print(text.rpartition("/")) # ('folder/sub', '/', 'file.txt')
# 주의: 기준값이 없으면 빈 문자열, 빈 문자열, 원본 반환
text = "hello-python"
print(text.rpartition("/")) # ('', '', 'hello-python')
28. removeprefix()
문자열.removeprefix(제거할값)
문자열 앞부분의 특정 값 제거
# 성공: 앞부분이 일치하면 제거
text = "user_123"
result = text.removeprefix("user_")
print(result) # 123
# 성공: URL 앞부분 제거
text = "<https://example.com>"
print(text.removeprefix("https://")) # example.com
# 주의: 앞부분이 일치하지 않으면 그대로 반환
text = "user_123"
print(text.removeprefix("admin_")) # user_123
# 주의: Python 3.9 이상부터 사용 가능
29. removesuffix()
문자열.removesuffix(제거할값)
문자열 끝부분의 특정 값 제거
# 성공: 끝부분이 일치하면 제거
text = "image.png"
result = text.removesuffix(".png")
print(result) # image
# 성공: 백업 확장자 제거
text = "data.csv.backup"
print(text.removesuffix(".backup")) # data.csv
# 주의: 끝부분이 일치하지 않으면 그대로 반환
text = "image.png"
print(text.removesuffix(".jpg")) # image.png
# 주의: Python 3.9 이상부터 사용 가능
30. swapcase()
문자열.swapcase()
대문자는 소문자로, 소문자는 대문자로 변경
# 성공: 대소문자 반전
text = "Hello Python"
result = text.swapcase()
print(result) # hELLO pYTHON
# 성공: 숫자와 특수문자는 그대로 유지
text = "Python3!"
print(text.swapcase()) # pYTHON3!
# 주의: 원본 문자열은 변경되지 않음
text = "Hello"
text.swapcase()
print(text) # Hello
31. casefold()
문자열.casefold()
대소문자 비교를 위해 문자열을 더 강하게 소문자화
# 성공: 일반 대문자를 소문자로 변경
text = "HELLO"
result = text.casefold()
print(result) # hello
# 성공: lower()보다 강한 소문자 변환
text = "Straße"
print(text.casefold()) # strasse
# 주의: 단순 출력용보다 대소문자 비교용으로 자주 사용
a = "Python"
b = "python"
print(a.casefold() == b.casefold()) # True
32. encode()
문자열.encode(인코딩)
문자열을 바이트로 변환
# 성공: 문자열을 UTF-8 바이트로 변환
text = "hello"
result = text.encode("utf-8")
print(result) # b'hello'
# 성공: 한글도 바이트로 변환
text = "안녕"
print(text.encode("utf-8")) # b'\\\\xec\\\\x95\\\\x88\\\\xeb\\\\x85\\\\x95'
# 주의: 결과는 문자열이 아니라 bytes 타입
text = "hello"
result = text.encode("utf-8")
print(type(result)) # <class 'bytes'>
33. format()
문자열.format(값)
문자열 안에 값을 넣기
# 성공: 중괄호 위치에 값 삽입
text = "Hello, {}"
result = text.format("Python")
print(result) # Hello, Python
# 성공: 여러 값 삽입
text = "{} + {} = {}"
print(text.format(1, 2, 3)) # 1 + 2 = 3
# 주의: 값 개수가 부족하면 에러 발생
text = "{} + {} = {}"
print(text.format(1, 2)) # IndexError
# 참고: 최근에는 f-string을 더 자주 사용
name = "Python"
print(f"Hello, {name}") # Hello, Python
34. format_map()
문자열.format_map(딕셔너리)
딕셔너리 값을 문자열 안에 넣기
# 성공: 딕셔너리 키를 이용해 값 삽입
data = {"name": "Kim", "age": 20}
result = "이름: {name}, 나이: {age}".format_map(data)
print(result) # 이름: Kim, 나이: 20
# 성공: 여러 키 사용 가능
data = {"lang": "Python", "level": "basic"}
print("{lang} 문법은 {level}부터 시작".format_map(data)) # Python 문법은 basic부터 시작
# 주의: 없는 키를 사용하면 에러 발생
data = {"name": "Kim"}
print("이름: {name}, 나이: {age}".format_map(data)) # KeyError
35. expandtabs()
문자열.expandtabs(칸수)
탭 문자를 공백으로 변환
# 성공: 탭을 기본 공백으로 변환
text = "a\\\\tb"
result = text.expandtabs()
print(result) # a b
# 성공: 탭 간격 지정 가능
text = "a\\\\tb"
print(text.expandtabs(4)) # a b
# 주의: 탭 문자 \\\\t가 있어야 효과 있음
text = "a b"
print(text.expandtabs(4)) # a b
36. maketrans() / translate()
변환표 = 문자열.maketrans(기존문자, 변경문자)
문자열.translate(변환표)
문자 단위로 여러 글자 변환
# 성공: 여러 문자를 한 번에 변경
text = "apple"
table = str.maketrans("ap", "AP")
result = text.translate(table)
print(result) # APPle
# 성공: 특정 문자 삭제
text = "a-b-c"
table = str.maketrans("", "", "-")
print(text.translate(table)) # abc
# 주의: 기존문자와 변경문자의 길이가 같아야 함
table = str.maketrans("abc", "XY")
# ValueError
37. replace(횟수 지정)
문자열.replace(기존값, 변경값, 횟수)
문자열을 지정한 횟수만큼만 치환
# 성공: 앞에서부터 1번만 변경
text = "apple apple apple"
result = text.replace("apple", "orange", 1)
print(result) # orange apple apple
# 성공: 앞에서부터 2번만 변경
text = "apple apple apple"
print(text.replace("apple", "orange", 2)) # orange orange apple
# 주의: 횟수를 생략하면 모두 변경
text = "apple apple apple"
print(text.replace("apple", "orange")) # orange orange orange
38. split(횟수 지정)
문자열.split(기준값, 횟수)
문자열을 지정한 횟수만큼만 나누기
# 성공: 앞에서부터 1번만 분리
text = "a,b,c,d"
result = text.split(",", 1)
print(result) # ['a', 'b,c,d']
# 성공: 앞에서부터 2번만 분리
text = "a,b,c,d"
print(text.split(",", 2)) # ['a', 'b', 'c,d']
# 주의: 횟수를 생략하면 모두 분리
text = "a,b,c,d"
print(text.split(",")) # ['a', 'b', 'c', 'd']
39. rsplit()
문자열.rsplit(기준값, 횟수)
오른쪽에서부터 문자열 나누기
# 성공: 오른쪽에서부터 1번만 분리
text = "2026-05-28"
result = text.rsplit("-", 1)
print(result) # ['2026-05', '28']
# 성공: 파일명과 확장자 분리
text = "report.final.pdf"
print(text.rsplit(".", 1)) # ['report.final', 'pdf']
# 주의: 횟수를 생략하면 split()과 결과가 같음
text = "a,b,c"
print(text.rsplit(",")) # ['a', 'b', 'c']
40. splitlines()
문자열.splitlines()
줄 단위로 문자열 나누기
# 성공: 줄바꿈 기준으로 분리
text = "hello\\\\npython\\\\njava"
result = text.splitlines()
print(result) # ['hello', 'python', 'java']
# 성공: 여러 종류의 줄바꿈 처리
text = "a\\\\r\\\\nb\\\\nc"
print(text.splitlines()) # ['a', 'b', 'c']
# 주의: 줄바꿈 문자는 결과에 포함되지 않음
text = "hello\\\\npython"
print(text.splitlines()) # ['hello', 'python']
# 참고: 줄바꿈 문자를 유지하려면 True 사용
print(text.splitlines(True)) # ['hello\\\\n', 'python']
41. islower()
문자열.islower()
문자열의 알파벳이 모두 소문자인지 확인
# 성공: 모두 소문자면 True
text = "hello"
result = text.islower()
print(result) # True
# 성공: 대문자가 섞이면 False
text = "Hello"
print(text.islower()) # False
# 주의: 숫자나 특수문자는 판단에서 제외됨
text = "hello123!"
print(text.islower()) # True
# 주의: 알파벳이 없으면 False
text = "123!"
print(text.islower()) # False
42. isupper()
문자열.isupper()
문자열의 알파벳이 모두 대문자인지 확인
# 성공: 모두 대문자면 True
text = "HELLO"
result = text.isupper()
print(result) # True
# 성공: 소문자가 섞이면 False
text = "HELLo"
print(text.isupper()) # False
# 주의: 숫자나 특수문자는 판단에서 제외됨
text = "HELLO123!"
print(text.isupper()) # True
# 주의: 알파벳이 없으면 False
text = "123!"
print(text.isupper()) # False
43. istitle()
문자열.istitle()
각 단어가 제목 형식인지 확인
# 성공: 각 단어의 첫 글자가 대문자면 True
text = "Hello Python"
result = text.istitle()
print(result) # True
# 성공: 첫 글자가 소문자면 False
text = "hello Python"
print(text.istitle()) # False
# 주의: 모든 단어가 제목 형식이어야 함
text = "Hello python"
print(text.istitle()) # False
# 주의: 숫자는 판단에 큰 영향 없음
text = "Python 3"
print(text.istitle()) # True
44. isnumeric()
문자열.isnumeric()
문자열이 숫자 문자로만 구성되어 있는지 확인
# 성공: 숫자로만 구성된 경우
text = "12345"
result = text.isnumeric()
print(result) # True
# 성공: 한자 숫자도 숫자로 판단
text = "四"
print(text.isnumeric()) # True
# 주의: 소수점은 숫자로 판단하지 않음
text = "3.14"
print(text.isnumeric()) # False
# 주의: 음수 기호도 숫자가 아님
text = "-10"
print(text.isnumeric()) # False
45. isdecimal()
문자열.isdecimal()
문자열이 10진수 숫자로만 구성되어 있는지 확인
# 성공: 일반 숫자는 True
text = "12345"
result = text.isdecimal()
print(result) # True
# 성공: 숫자가 아닌 문자가 섞이면 False
text = "123a"
print(text.isdecimal()) # False
# 주의: 한자 숫자는 False
text = "四"
print(text.isdecimal()) # False
# 주의: 소수점과 음수 기호도 False
text = "3.14"
print(text.isdecimal()) # False
46. isidentifier()
문자열.isidentifier()
문자열이 변수명으로 사용할 수 있는 형태인지 확인
# 성공: 변수명으로 사용 가능한 문자열
text = "user_name"
result = text.isidentifier()
print(result) # True
# 성공: 숫자로 시작하면 False
text = "1user"
print(text.isidentifier()) # False
# 주의: 공백이나 특수문자가 있으면 False
text = "user name"
print(text.isidentifier()) # False
text = "user-name"
print(text.isidentifier()) # False
47. isprintable()
문자열.isprintable()
문자열이 출력 가능한 문자로만 구성되어 있는지 확인
# 성공: 일반 문자는 True
text = "hello python"
result = text.isprintable()
print(result) # True
# 성공: 빈 문자열도 True
text = ""
print(text.isprintable()) # True
# 주의: 줄바꿈 문자는 출력 불가능 문자로 판단
text = "hello\\\\npython"
print(text.isprintable()) # False
# 주의: 탭 문자도 False
text = "hello\\\\tpython"
print(text.isprintable()) # False
48. ascii()
ascii(문자열)
문자열을 ASCII 표현 형태로 반환
# 성공: 한글을 이스케이프 표현으로 변환
text = "안녕"
result = ascii(text)
print(result) # '\\\\uc548\\\\ub155'
# 성공: 영어는 그대로 표현
text = "hello"
print(ascii(text)) # 'hello'
# 주의: 문자열 메서드가 아니라 내장 함수
text = "안녕"
print(text.ascii()) # AttributeError
49. len()
len(문자열)
문자열 길이 구하기
# 성공: 문자열의 글자 수 반환
text = "hello"
result = len(text)
print(result) # 5
# 성공: 한글도 글자 수 기준
text = "안녕하세요"
print(len(text)) # 5
# 주의: 공백도 길이에 포함됨
text = "hello python"
print(len(text)) # 12
# 주의: 문자열 메서드가 아니라 내장 함수
text = "hello"
print(text.len()) # AttributeError
50. ord()
ord(문자)
문자를 유니코드 숫자 값으로 변환
# 성공: 문자 하나를 숫자로 변환
text = "A"
result = ord(text)
print(result) # 65
# 성공: 한글도 유니코드 값 반환
text = "가"
print(ord(text)) # 44032
# 주의: 문자 하나만 가능
text = "AB"
print(ord(text)) # TypeError
51. chr()
chr(숫자)
유니코드 숫자 값을 문자로 변환
# 성공: 숫자를 문자로 변환
num = 65
result = chr(num)
print(result) # A
# 성공: 한글 유니코드 값도 변환
num = 44032
print(chr(num)) # 가
# 주의: 유효한 유니코드 범위 숫자만 가능
num = 999999999
print(chr(num)) # ValueError
52. in
값 in 문자열
문자열 안에 특정 값이 포함되어 있는지 확인
# 성공: 포함되어 있으면 True
text = "hello python"
result = "python" in text
print(result) # True
# 성공: 포함되어 있지 않으면 False
text = "hello python"
print("java" in text) # False
# 주의: 대소문자를 구분함
text = "Hello Python"
print("python" in text) # False
53. not in
값 not in 문자열
문자열 안에 특정 값이 없는지 확인
# 성공: 포함되어 있지 않으면 True
text = "hello python"
result = "java" not in text
print(result) # True
# 성공: 포함되어 있으면 False
text = "hello python"
print("python" not in text) # False
# 주의: 대소문자를 구분함
text = "Hello Python"
print("python" not in text) # True
54. 문자열 인덱싱
문자열[위치]
문자열에서 특정 위치의 문자 가져오기
# 성공: 첫 번째 문자 가져오기
text = "python"
result = text[0]
print(result) # p
# 성공: 마지막 문자 가져오기
text = "python"
print(text[-1]) # n
# 주의: 존재하지 않는 위치는 에러 발생
text = "python"
print(text[10]) # IndexError
55. 문자열 슬라이싱
문자열[시작:끝]
문자열에서 원하는 범위만 잘라내기
# 성공: 0번부터 2번 앞까지 자르기
text = "python"
result = text[0:2]
print(result) # py
# 성공: 시작 또는 끝 생략 가능
text = "python"
print(text[:3]) # pyt
print(text[3:]) # hon
# 주의: 끝 위치는 포함되지 않음
text = "python"
print(text[1:4]) # yth
# 주의: 원본 문자열은 변경되지 않음
text = "python"
text[0:2]
print(text) # python
56. 문자열 슬라이싱 step
문자열[시작:끝:간격]
간격을 두고 문자열 자르기
# 성공: 2칸씩 건너뛰기
text = "abcdef"
result = text[::2]
print(result) # ace
# 성공: 문자열 뒤집기
text = "python"
print(text[::-1]) # nohtyp
# 주의: 간격이 0이면 에러 발생
text = "abcdef"
print(text[::0]) # ValueError
57. 문자열 더하기
문자열 + 문자열
문자열끼리 연결하기
# 성공: 문자열 연결
a = "hello"
b = "python"
result = a + " " + b
print(result) # hello python
# 성공: 변수와 문자열 연결
name = "Kim"
print("Hello, " + name) # Hello, Kim
# 주의: 문자열과 숫자는 바로 더할 수 없음
age = 20
print("나이: " + age) # TypeError
# 해결: 숫자를 문자열로 변환
print("나이: " + str(age)) # 나이: 20
58. 문자열 곱하기
문자열 * 숫자
문자열 반복하기
# 성공: 문자열 3번 반복
text = "ha"
result = text * 3
print(result) # hahaha
# 성공: 구분선 만들기
line = "-"
print(line * 10) # ----------
# 주의: 문자열끼리는 곱할 수 없음
text = "ha"
print(text * "3") # TypeError
59. 문자열 비교
문자열1 == 문자열2
문자열1 != 문자열2
문자열이 같은지 다른지 비교
# 성공: 문자열이 같으면 True
a = "python"
b = "python"
print(a == b) # True
# 성공: 문자열이 다르면 True
a = "python"
b = "java"
print(a != b) # True
# 주의: 대소문자를 구분함
a = "Python"
b = "python"
print(a == b) # False
60. 문자열 크기 비교
문자열1 < 문자열2
문자열1 > 문자열2
문자열을 유니코드 순서 기준으로 비교
# 성공: 알파벳 순서 비교
a = "apple"
b = "banana"
print(a < b) # True
# 성공: 앞 글자부터 차례대로 비교
a = "abc"
b = "abd"
print(a < b) # True
# 주의: 대문자와 소문자는 순서가 다름
a = "A"
b = "a"
print(a < b) # True
61. 문자열 반복문
for 변수 in 문자열:
실행문
문자열을 한 글자씩 반복
# 성공: 한 글자씩 출력
text = "abc"
for ch in text:
print(ch)
# a
# b
# c
# 주의: 문자열 자체는 변경되지 않음
text = "abc"
for ch in text:
ch = ch.upper()
print(text) # abc
62. enumerate()
enumerate(문자열)
문자열의 위치와 문자를 함께 가져오기
# 성공: 인덱스와 문자 함께 출력
text = "abc"
for index, ch in enumerate(text):
print(index, ch)
# 0 a
# 1 b
# 2 c
# 주의: enumerate 결과는 바로 출력하면 객체로 보임
text = "abc"
print(enumerate(text)) # <enumerate object at ...>
# 확인하려면 list로 변환
print(list(enumerate(text))) # [(0, 'a'), (1, 'b'), (2, 'c')]
63. f-string
f"문자열 {변수}"
문자열 안에 변수 값을 바로 넣기
# 성공: 변수 값 삽입
name = "Kim"
result = f"Hello, {name}"
print(result) # Hello, Kim
# 성공: 계산식 사용 가능
a = 10
b = 20
print(f"{a} + {b} = {a + b}") # 10 + 20 = 30
# 주의: 문자열 앞에 f를 붙여야 함
name = "Kim"
print("Hello, {name}") # Hello, {name}
64. format 문자열 정렬
f"{값:정렬방식}"
문자열 정렬 및 폭 지정
# 성공: 오른쪽 정렬
text = "hi"
print(f"{text:>10}") # hi
# 성공: 왼쪽 정렬
print(f"{text:<10}") # hi
# 성공: 가운데 정렬
print(f"{text:^10}") # hi
# 주의: 전체 길이보다 길면 그대로 출력
text = "hello"
print(f"{text:>3}") # hello
65. format 숫자 자리수
f"{숫자:자리수}"
숫자 출력 자리수 지정
# 성공: 소수점 자리수 지정
num = 3.141592
print(f"{num:.2f}") # 3.14
# 성공: 전체 자리수 지정
num = 42
print(f"{num:5}") # 42
# 주의: 숫자 형식은 숫자 타입에 사용
text = "hello"
print(f"{text:.2f}") # ValueError
66. format 천 단위 콤마
f"{숫자:,}"
숫자에 천 단위 콤마 추가
# 성공: 천 단위 콤마 출력
num = 1000000
print(f"{num:,}") # 1,000,000
# 성공: 실수에도 가능
num = 1234567.89
print(f"{num:,}") # 1,234,567.89
# 주의: 문자열에는 사용할 수 없음
text = "1000000"
print(f"{text:,}") # ValueError
67. raw string
r"문자열"
이스케이프 문자를 무시하고 그대로 사용
# 성공: 경로 문자열 표현
path = r"C:\\\\python\\\\test"
print(path) # C:\\\\python\\\\test
# 성공: \\\\n도 줄바꿈 처리 안 함
text = r"hello\\\\npython"
print(text) # hello\\\\npython
# 주의: 마지막 문자를 \\\\로 끝낼 수 없음
path = r"C:\\\\python\\\\"
print(path) # SyntaxError
68. escape 문자
\\\\n
\\\\t
\\\\"
\\\\\\\\
특수 기능을 가진 문자
# 성공: 줄바꿈
print("hello\\\\npython")
# hello
# python
# 성공: 탭
print("hello\\\\tpython")
# hello python
# 성공: 큰따옴표 출력
print("\\\\"hello\\\\"") # "hello"
# 성공: 역슬래시 출력
print("\\\\\\\\") # \\\\
# 주의: 역슬래시는 escape 시작 문자
path = "C:\\\\new"
print(path)
# \\\\n 이 줄바꿈으로 처리될 수 있음
69. 문자열 여러 줄 작성
"""문자열"""
'''문자열'''
여러 줄 문자열 작성
# 성공: 여러 줄 문자열 저장
text = """hello
python
java"""
print(text)
# hello
# python
# java
# 성공: 작은따옴표 3개도 가능
text = '''apple
banana'''
print(text)
# apple
# banana
# 주의: 줄바꿈도 문자열에 포함됨
text = """hello
python"""
print(len(text)) # 12
'🐍Python' 카테고리의 다른 글
| Python Basic: set (0) | 2026.05.28 |
|---|---|
| Python Basic: dict (0) | 2026.05.28 |
| Python Basic: tuple (0) | 2026.05.28 |
| Python Basic: list (0) | 2026.05.28 |
