본문 바로가기

언어/Python

[ 파이썬 / Python ] splite() 함수 사용하기

반응형

Python의 split() 메서드는 문자열을 특정 구분자를 기준으로 나누어 리스트로 반환하는 매우 유용한 함수입니다.

1. 기본 사용법

기본적으로 split() 메서드는 공백을 기준으로 문자열을 나눕니다.

s = "Hello world this is Python"
words = s.split()
print(words)  # 출력: ['Hello', 'world', 'this', 'is', 'Python']

2. 특정 구분자로 문자열 나누기

특정 구분자를 지정하여 문자열을 나눌 수 있습니다.

s = "apple,banana,cherry"
fruits = s.split(",")
print(fruits)  # 출력: ['apple', 'banana', 'cherry']

3. 최대 분할 횟수 지정하기

split() 메서드의 두 번째 인자로 maxsplit을 사용하여 분할 횟수를 제한할 수 있습니다.

s = "apple,banana,cherry,orange"
fruits = s.split(",", 2)
print(fruits)  # 출력: ['apple', 'banana', 'cherry,orange']

4. 여러 구분자로 문자열 나누기

여러 구분자를 사용하여 문자열을 나누려면 re.split()을 사용해야 합니다.

import re

s = "apple;banana,orange|grape"
fruits = re.split(r"[;,\|]", s)
print(fruits)  # 출력: ['apple', 'banana', 'orange', 'grape']

5. 문자열의 시작과 끝의 공백 제거 후 나누기

split() 메서드는 기본적으로 문자열 양 끝의 공백을 제거하고 나눕니다.

s = "  Hello  world  "
words = s.split()
print(words)  # 출력: ['Hello', 'world']

6. 여러 개의 연속된 공백으로 나누기

여러 개의 연속된 공백을 하나의 구분자로 간주하여 문자열을 나눌 수 있습니다.

s = "Hello   world  this  is  Python"
words = s.split()
print(words)  # 출력: ['Hello', 'world', 'this', 'is', 'Python']

7. 줄바꿈 문자로 문자열 나누기

줄바꿈 문자 \n을 기준으로 문자열을 나눌 수 있습니다.

s = "Hello\nworld\nthis\nis\nPython"
lines = s.split("\n")
print(lines)  # 출력: ['Hello', 'world', 'this', 'is', 'Python']

8. 여러 줄 문자열을 줄바꿈 문자로 나누기

s = """Hello
world
this
is
Python"""
lines = s.splitlines()
print(lines)  # 출력: ['Hello', 'world', 'this', 'is', 'Python']

9. 특정 패턴으로 문자열 나누기

정규 표현식을 사용하여 특정 패턴으로 문자열을 나눌 수 있습니다.

import re

s = "apple1banana2cherry3orange"
fruits = re.split(r"\d", s)
print(fruits)  # 출력: ['apple', 'banana', 'cherry', 'orange']

10. 예제 요약

  1. 기본 공백 기준 분할:
    "Hello world this is Python".split()
  2. 특정 구분자 기준 분할:
    "apple,banana,cherry".split(",")
  3. 최대 분할 횟수 지정:
    "apple,banana,cherry,orange".split(",", 2)
  4. 여러 구분자 기준 분할:
     re.split(r"[;,\|]", "apple;banana,orange|grape")
  5. 공백 제거 후 분할:
    "  Hello  world  ".split()
  6. 여러 개의 연속된 공백 기준 분할:
    "Hello   world  this  is  Python".split()
  7. 줄바꿈 문자 기준 분할:
    "Hello\nworld\nthis\nis\nPython".split("\n")
  8. 여러 줄 문자열 분할:
    """Hello
     world
     this
     is
     Python""".splitlines()
  9. 특정 패턴 기준 분할:
     re.split(r"\d", "apple1banana2cherry3orange")
반응형