파이썬 시퀀스 객체의 주요 메소드와 활용법

YeHee·2024년 12월 16일

⏰ 2024.12.13 (D+47)

1. 파이썬 시퀀스 객체의 정의

  • 파이썬에서 시퀀스 객체는 문자열(str), 리스트(list), 튜플(tuple), 범위(range) 등과 같이 순서가 있는 자료형
  • 이러한 시퀀스 객체들은 공통된 기능을 제공하며, 이를 활용하면 데이터 처리와 조작이 더욱 효율적

2. join() 메소드

  • join( ) 메소드는 반복 가능한 객체(iterable)의 요소들을 지정한 구분자로 연결하여 하나의 문자열로 반환
  • 이때, 연결하려는 모든 요소는 문자열이어야 한다
mountains = ['한라산', '설악산', '대둔산', '덕유산']
mountains_str = '▲'.join(mountains)
print(mountains_str)  # 출력: 한라산▲설악산▲대둔산▲덕유산

만약 리스트에 숫자와 문자열이 혼합되어 있다면,
join() 메소드를 사용하기 전에 모든 요소를 문자열로 변환

mountains = ['한라산', '설악산', '대둔산', '덕유산', 2024]
mountains_str = '▲'.join(map(str, mountains))
print(mountains_str)  # 출력: 한라산▲설악산▲대둔산▲덕유산▲2024

3. split() 메소드

  • split() 메소드는 문자열을 지정한 구분자를 기준으로 분리하여 리스트로 반환
  • 구분자를 지정하지 않으면 공백을 기준으로 분리
mountains_str = '한라산▲설악산▲대둔산▲덕유산'
mountains = mountains_str.split('▲')
print(mountains)  # 출력: ['한라산', '설악산', '대둔산', '덕유산']
  • 구분자를 지정하지 않으면 공백을 기준으로 분리
text = 'Hello World Python'
words = text.split()
print(words)  # 출력: ['Hello', 'World', 'Python']

4. replace() 메소드

  • replace() 메소드는 문자열 내에서 지정한 부분을 다른 문자열로 교체
text = 'Hello World'
new_text = text.replace('World', 'Python')
print(new_text)  # 출력: Hello Python

5. upper() 메소드

  • upper() 메소드는 문자열의 모든 문자를 대문자로 변환
text = 'Hello World'
upper_text = text.upper()
print(upper_text)  # 출력: HELLO WORLD

6. lstrip(), rstrip(), strip() 메소드

  • 이 메소드들은 문자열의 왼쪽, 오른쪽, 양쪽에서 지정한 문자를 제거
  • 지정하지 않으면 공백을 제거
text = '   Hello World   '
left_stripped = text.lstrip()
right_stripped = text.rstrip()
both_stripped = text.strip()
print(f'X{left_stripped}X')  # 출력: XHello World   X
print(f'X{right_stripped}X')  # 출력: X   Hello WorldX
print(f'X{both_stripped}X')  # 출력: XHello WorldX

7. zfill() 메소드

  • zfill() 메소드는 문자열의 왼쪽에 0을 채워 지정한 길이의 문자열
number = '9'
filled_number = number.zfill(2)
print(filled_number)  # 출력: 09

8. find()와 rfind() 메소드

  • find() 메소드는 지정한 문자열이 처음으로 나타나는 인덱스를 반환
  • 없으면 -1을 반환합니다. rfind()는 마지막으로 나타나는 인덱스를 반환
text = 'Hello, He is a good person.'
index = text.find('He')
print(index)  # 출력: 0
last_index = text.rfind('He')
print(last_index)  # 출력: 15

9. index()와 rindex() 메소드

  • index() 메소드는 지정한 문자열이 처음으로 나타나는 인덱스를 반환
  • 없으면 ValueError를 발생시킨다
  • rindex()는 마지막으로 나타나는 인덱스를 반환
text = 'Hello, He is a good person.'
index = text.index('He')
print(index)  # 출력: 0
last_index = text.rindex('He')
print(last_index)  # 출력: 15

10. count() 메소드

  • count() 메소드는 지정한 문자열이 몇 번 나타나는지 세어 반환
text = 'Hello, He is a good person.'
count = text.count('He')
print(count)  # 출력: 2

0개의 댓글