1. 문자열(String)이란?
문자열은 문자의 집합으로, 작은따옴표(') 또는 큰따옴표(")로 감싸서 만든다.
text1 = "Hello Python"
text2 = 'AI Engineering'
- 순서 있음 → 인덱스와 슬라이싱 가능
- 불변(Immutable) → 한 번 생성되면 수정 불가
- 반복문, 메서드를 이용해 가공 가능
2. 인덱싱과 슬라이싱
2.1 인덱싱
text = "Python"
print(text[0]) # P
print(text[-1]) # n
- 0부터 시작하는 인덱스 번호로 접근
- 음수 인덱스로 뒤에서 접근 가능
2.2 슬라이싱
word = "Artificial"
print(word[0:4]) # Arti
print(word[:6]) # Artifi
print(word[3:]) # ificial
print(word[::2]) # Atfca
[시작:끝]→ 시작 이상, 끝 미만[::간격]→ 일정 간격으로 추출
3. 문자열 연산
문자열은 여러 가지 연산이 가능하다.
a = "Hello"
b = "World"
print(a + b) # HelloWorld (연결)
print(a * 3) # HelloHelloHello (반복)
print("H" in a) # True (포함 여부)
+: 문자열 연결*: 문자열 반복in: 특정 문자 포함 여부 검사
4. 주요 메서드
문자열은 다양한 메서드를 제공한다.
text = " python programming "
print(text.upper()) # 대문자 변환
print(text.lower()) # 소문자 변환
print(text.strip()) # 앞뒤 공백 제거
print(text.replace("python", "AI")) # 문자열 치환
print(text.split()) # 공백 기준 분리
upper(): 대문자로 변환lower(): 소문자로 변환strip(): 양쪽 공백 제거replace(old, new): 문자열 치환split(): 문자열을 리스트로 분리
5. 탐색 관련 메서드
txt = "banana"
print(txt.find("na")) # 2 (처음 위치)
print(txt.rfind("na")) # 4 (마지막 위치)
print(txt.count("a")) # 3
find(): 부분 문자열 처음 위치rfind(): 마지막 위치count(): 등장 횟수
6. 문자열 포맷팅
6.1 f-string (추천 방식)
name = "Yuju"
age = 22
print(f"My name is {name}, I am {age} years old.")
6.2 format()
print("My name is {}, I am {} years old.".format("Yuju", 22))
6.3 % 연산자
print("My name is %s, I am %d years old." % ("Yuju", 22))
7. 반복문과 문자열
문자열도 반복문을 통해 문자 하나씩 다룰 수 있다.
for ch in "AI":
print(ch)
8. 불변성(Immutable)
문자열은 불변 자료형이므로 특정 문자를 직접 바꿀 수 없다.
s = "Python"
# s[0] = "J" # 오류 발생
s = "J" + s[1:]
print(s) # Jython