파이썬 문자열 split() 메서드
예시
문자열을 각 단어가 목록 항목인 목록으로 분할합니다.
txt = "welcome to the jungle"
x = txt.split()
print(x)
정의 및 사용
이 split()
메서드는 문자열을 목록으로 분할합니다.
구분 기호를 지정할 수 있으며 기본 구분 기호는 공백입니다.
참고: maxsplit이 지정되면 목록에는 지정된 수의 요소 와 1 이 포함 됩니다.
통사론
string.split(separator, maxsplit)
매개변수 값
Parameter | Description |
---|---|
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences" |
더 많은 예
예시
쉼표와 공백을 구분 기호로 사용하여 문자열을 분할합니다.
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(", ")
print(x)
예시
해시 문자를 구분 기호로 사용:
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
예시
문자열을 최대 2개의 항목이 있는 목록으로 분할합니다.
txt = "apple#banana#cherry#orange"
# setting the maxsplit parameter
to 1, will return a list with 2 elements!
x = txt.split("#", 1)
print(x)