Python

[Python] 시퀀스 - 문자열(string)

디지몬진화 2024. 6. 14. 19:35

1. 문자열 알아보기

- 문자들의 시퀀스

- 프로그래밍에서 빈번하게 다루어지는 데이터 형식

- 변경이 불가능한 객체

 

2. 문자열 예시

s1 = str("Hello")
s2 = "Hello“
s1 = "Hello"
s2 = "World"
s3 = "Hello"+"World"

 

3. 개별 문자 접근하기

- 인덱싱(Indexing) : 문자열에 []을 붙여서 문자를 추출

>>> word = 'abcdef'
>>> word[0]
'a'
>>> word[5]
'f'

 

- 슬라이싱(slicing) : 콜론(:)을 이용하여 특정한 구간 지정

>>> s="Hello World"
>>> s[0:5]
'Hello'
>>> word = 'Python'
>>> word[:2]
'Py'
>>> word[4:]
'on'
>>> word[:]
'Python’

 

4. in 연산자

- in 연산자 : 문자열 안에 다른 문자열이 있는지 확인

>>> s="Love will find a way."
>>> "Love" in s
True
>>> "love" in s
False

 

5. 문자열 비교하기

- 사전에서 오는 순서대로 적용 (어떤 문자열이 사전에서 앞에 있으면 '<' 연산자를 적용했을 때, 참이 됨)

>>> "apple" < "banana"
True

 

 

6. 반복하여 문자 처리하기

# 모든 문자를 하나씩 출력하는 코드
>>> s = input("문자열을 입력하시오")
>>> for c in s :
        print(c)
#문자열 안의 문자들을 특정한 순서로 방문
s = input("문자열을 입력하시오")
for i in range(1, len(s), 2) :
    print(s[i])

 

 

7. 문자열에서 단어 분리

- split() : 문자열 안의 단어를 분리하여 리스트로 만들어서 반환

>>> s = 'Never put off till tomorrow what you can do today.'
>>> s.split()
['Never', 'put', 'off', 'till', 'tomorrow', 'what', 'you', 'can', 'do', 'today.']

>>> s = 'apple, banana, orange'
>>> result = s.split(', ')
>>> print(result)
['apple', 'banana', 'orange']

 

 

8. join() 메소드

- join() 메소드 : 리스트나 튜플의 각 요소를 구분자 문자열과 함께 결합하여 하나의 문자열로 만듦

>>> my_list = ["apple", "banana", "orange"]
>>> result = ", ".join(my_list)
>>> print(result)
apple, banana, orange

 

 

9. 문자열 검사

- isalpha() : 문자열이 문자로만 구성되어 있는지 검사

- isdigit() : 문자열이 숫자로만 구성되어 있는지 검사

>>> s="abcdef"
>>> s.isalpha()
True
>>> s="123456"
>>> s.isdigit()
True

 

 

10. 부분 문자열 검색

- startswith() : 지정된 문자열로 시작하는지 판단해 불(bool)값을 출력

- endswith() : 지정된 문자열로 끝나는지 판단해 불(bool)값을 출력

s = input("파이썬 소스 파일 이름을 입력하시오: ")
if s.endswith(".py"):
    print("올바른 파일 이름입니다")
else :
    print("올바른 파일 이름이 아닙니다.")

 

- find() : 지정된 문자열을 찾아 그 첫 인덱스를 내줌 (탐색 방향은 왼쪽에서 오른쪽)

>>> s = "findletter"
>>> print(s.find("d"))
3

 

 

11. 문자열에서 공백 문자 제거하기

- strip() : 공백 문자 제거

>>> s = " Little by little the little bird builds its nest"
>>> s.strip()
'Little by little the little bird builds its nest'

 

 

12. 부분 문자열 개수 세기

- count() : 지정된 문자열을 찾아 개수를 출력

>>> arr = [1,2,1,3,1]
>>> print(a.count(1)) 
3
>>> text = "apple orange apple banana apple"

>>> count_apple = text.count("apple")
>>> print(count_apple)
3

>>> count_fruit = text.count("fruit")
>>> print(count_fruit)
0

>>> count_a = text.count("a", 4, 15)
>>> print(count_a)
2