IT

[Python] split() 함수의 정의와 예제

feelninefree 2024. 11. 19. 21:05
반응형

split() 함수는 Python 문자열 메서드 중 하나로, 문자열을 특정 구분자를 기준으로 나누어 리스트 형태로 반환합니다. 기본적으로 공백을 기준으로 문자열을 분리하며, 구분자를 사용자 지정할 수도 있습니다.

문법

string.split(separator, maxsplit)

매개변수

  1. separator (선택적): 문자열을 나눌 기준이 되는 구분자입니다. 기본값은 공백(' ')입니다.
  2. maxsplit (선택적): 나눌 최대 횟수를 지정합니다. 지정하지 않으면 전체 문자열을 분리합니다.

반환값

  • 분리된 문자열의 리스트를 반환합니다.

예제

1. 공백을 기준으로 문자열 나누기

text = "Python is a great programming language" 
result = text.split() 
print(result)

 

출력:

['Python', 'is', 'a', 'great', 'programming', 'language']

2. 특정 구분자를 기준으로 나누기

text = "apple,banana,cherry" 
result = text.split(',') 
print(result)

 

출력:

['apple', 'banana', 'cherry']

3. 최대 분리 횟수 지정

text = "one two three four" 
result = text.split(' ', 2) 
print(result)

 

출력:

['one', 'two', 'three four']

4. 구분자를 포함하지 않을 때 (공백 제거)

text = " hello world " 
result = text.split() 
print(result)

 

출력:

['hello', 'world']

5. 줄바꿈 문자(\n)로 나누기

text = "line1\nline2\nline3" 
result = text.split('\n') 
print(result)

 

출력:

['line1', 'line2', 'line3']

참고

split() 메서드는 문자열 끝에 구분자가 있더라도 빈 문자열을 반환하지 않습니다.

text = "apple,banana,cherry," 
result = text.split(',') 
print(result)

 

출력:

['apple', 'banana', 'cherry', '']

 

 이 게시글은 chatgpt-4o 의 도움을 받아 작성되었습니다.

반응형