⏰ 2024.12.13 (D+47)
- join( ) 메소드는 반복 가능한 객체(iterable)의 요소들을 지정한 구분자로 연결하여 하나의 문자열로 반환
- 이때, 연결하려는 모든 요소는 문자열이어야 한다
mountains = ['한라산', '설악산', '대둔산', '덕유산'] mountains_str = '▲'.join(mountains) print(mountains_str) # 출력: 한라산▲설악산▲대둔산▲덕유산만약 리스트에 숫자와 문자열이 혼합되어 있다면,
join() 메소드를 사용하기 전에 모든 요소를 문자열로 변환mountains = ['한라산', '설악산', '대둔산', '덕유산', 2024] mountains_str = '▲'.join(map(str, mountains)) print(mountains_str) # 출력: 한라산▲설악산▲대둔산▲덕유산▲2024
- split() 메소드는 문자열을 지정한 구분자를 기준으로 분리하여 리스트로 반환
- 구분자를 지정하지 않으면 공백을 기준으로 분리
mountains_str = '한라산▲설악산▲대둔산▲덕유산' mountains = mountains_str.split('▲') print(mountains) # 출력: ['한라산', '설악산', '대둔산', '덕유산']
- 구분자를 지정하지 않으면 공백을 기준으로 분리
text = 'Hello World Python' words = text.split() print(words) # 출력: ['Hello', 'World', 'Python']
- replace() 메소드는 문자열 내에서 지정한 부분을 다른 문자열로 교체
text = 'Hello World' new_text = text.replace('World', 'Python') print(new_text) # 출력: Hello Python
- upper() 메소드는 문자열의 모든 문자를 대문자로 변환
text = 'Hello World' upper_text = text.upper() print(upper_text) # 출력: HELLO WORLD
- 이 메소드들은 문자열의 왼쪽, 오른쪽, 양쪽에서 지정한 문자를 제거
- 지정하지 않으면 공백을 제거
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
- zfill() 메소드는 문자열의 왼쪽에 0을 채워 지정한 길이의 문자열
number = '9' filled_number = number.zfill(2) print(filled_number) # 출력: 09
- 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
- 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
- count() 메소드는 지정한 문자열이 몇 번 나타나는지 세어 반환
text = 'Hello, He is a good person.' count = text.count('He') print(count) # 출력: 2