파이썬에서 문자열(str) 은 텍스트 데이터를 저장하고 조작하기 위한 가장 기본적인 자료형입니다. 문자열은 불변(immutable) 자료형으로, 생성된 후에는 수정할 수 없습니다. 하지만 다양한 내장 메서드를 통해 쉽게 조작하고 변환할 수 있습니다.
1. 문자열 생성
| |
| str1 = "Hello, Python!" |
| str2 = 'Welcome to the world of coding.' |
| |
| |
| multiline_str = """This is |
| a multiline |
| string.""" |
| |
| |
| empty_str = "" |
| |
| print(str1) |
| print(multiline_str) |
| |
결과:
| Hello, Python! |
| This is |
| a multiline |
| string. |
| |
문자열은 큰따옴표(")나 작은따옴표(')로 생성할 수 있으며, 여러 줄 문자열은 삼중 따옴표(""" 또는 ''')를 사용합니다.
2. 문자열 인덱싱과 슬라이싱
| str1 = "Hello, Python!" |
| |
| |
| print(str1[0]) # 첫 번째 문자 |
| print(str1[-1]) # 마지막 문자 |
| |
| |
| print(str1[0:5]) # 0번 인덱스부터 4번까지 |
| print(str1[7:]) # 7번 인덱스부터 끝까지 |
| print(str1[::-1]) # 문자열 뒤집기 |
| |
결과:
| H |
| ! |
| Hello |
| Python! |
| !nohtyP ,olleH |
| |
문자열은 순서가 있는 자료형으로, 인덱스를 통해 특정 문자에 접근하거나 슬라이싱으로 부분 문자열을 추출할 수 있습니다.
3. 문자열 결합과 반복
| str1 = "Hello" |
| str2 = "World" |
| |
| |
| combined = str1 + " " + str2 |
| print(combined) |
| |
| |
| repeated = str1 * 3 |
| print(repeated) |
| |
결과:
| Hello World |
| HelloHelloHello |
| |
문자열은 + 연산자를 사용해 결합하거나, * 연산자를 사용해 반복할 수 있습니다.
4. 문자열의 주요 메서드
대소문자 변환
| text = "Python Is Amazing" |
| |
| print(text.upper()) |
| print(text.lower()) |
| print(text.capitalize()) |
| print(text.title()) |
| |
결과:
| PYTHON IS AMAZING |
| python is amazing |
| Python is amazing |
| Python Is Amazing |
| |
공백 제거
| text = " Hello, Python! " |
| print(text.strip()) |
| print(text.lstrip()) |
| print(text.rstrip()) |
| |
결과:
| Hello, Python! |
| Hello, Python! |
| Hello, Python! |
| |
문자열 대체
| text = "I love Java" |
| print(text.replace("Java", "Python")) |
| |
결과:
문자열 분리와 결합
| text = "apple,banana,cherry" |
| print(text.split(",")) |
| |
| fruits = ["apple", "banana", "cherry"] |
| print(", ".join(fruits)) |
| |
결과:
| ['apple', 'banana', 'cherry'] |
| apple, banana, cherry |
| |
5. 문자열 검색
| text = "Python is fun" |
| |
| print(text.find("is")) # "is"의 첫 번째 위치 반환 |
| print(text.find("Java")) # 없으면 -1 반환 |
| print(text.count("n")) # "n"의 개수 반환 |
| print(text.startswith("Python")) # "Python"으로 시작하는지 확인 |
| print(text.endswith("fun")) # "fun"으로 끝나는지 확인 |
| |
결과:
6. 문자열 서식 지정
format 메서드 사용
| name = "Alice" |
| age = 25 |
| text = "My name is {} and I am {} years old.".format(name, age) |
| print(text) |
| |
결과:
| My name is Alice and I am 25 years old. |
| |
f-string (Python 3.6+)
| name = "Alice" |
| age = 25 |
| text = f"My name is {name} and I am {age} years old." |
| print(text) |
| |
결과:
| My name is Alice and I am 25 years old. |
| |
7. 문자열의 불변성
| text = "Hello" |
| |
| |
| |
| text = "h" + text[1:] |
| print(text) |
| |
결과:
문자열은 불변 자료형이므로 수정할 수 없습니다. 대신 새로운 문자열을 생성해야 합니다.
8. 문자열 관련 내장 함수
문자열 길이 확인
| text = "Hello, Python!" |
| print(len(text)) |
| |
결과:
ASCII 값과 문자 변환
| print(ord("A")) |
| print(chr(65)) |
| |
결과:
9. 문자열 활용 예제
문자열 뒤집기
| text = "Python" |
| reversed_text = text[::-1] |
| print(reversed_text) |
| |
결과:
특정 문자 제거
| text = "Hello, World!" |
| cleaned_text = text.replace(",", "") |
| print(cleaned_text) |
| |
결과:
요약: 문자열의 세계는 끝이 없다!
- 문자열 생성: 큰따옴표, 작은따옴표, 삼중 따옴표로 생성 가능.
- 인덱싱과 슬라이싱: 특정 문자에 접근하거나 부분 문자열 추출 가능.
- 메서드 활용: 대소문자 변환, 공백 제거, 검색, 대체 등 다양한 조작 가능.
- 서식 지정: format과 f-string으로 유연한 출력 구현.
- 불변성: 문자열은 수정 불가. 새로운 문자열 생성 필요.
파이썬 문자열은 유연하고 강력한 도구로, 텍스트 처리에서 그 진가를 발휘합니다. 실험을 통해 문자열의 세계를 더 깊이 탐구해보세요! 🚀