본문 바로가기

프로그래밍/Python

[Python] split()과 split(' ')의 차이

split()
split(' ')
*split('') -> 띄어쓰기가 있어야 함! 이렇게 하면 에러뜸! (ValueError: empty separator)

1. split()

모든 공백을 지운다. 개수상관없이.
공백을 한번에 처리.

예시

strings = input()
words_list = strings.split()
print(words_list)

입력 : ..two.one...threetwo.. (.은 스페이스로 간주)
출력 : ['two', 'one', 'threetwo']

2. split(' ')

공백을 따로따로 처리.

  • 문자열 사이에 있는 공백 하나 : 분할점으로 이용. 그 공백은 지움.
  • 공백이 연속으로 나오는 경우 : 일반 문자 다음에 오는 공백만 지우고 나머지 공백은 리스트의 하나의 요소가 됨.
  • 마지막에 공백 : 마지막에 분할할 요소가 없다면(문자 더이상 없을때) 남은 공백들은 모두 지움.

예시

strings = input()
words_list = strings.split(' ')
print(words_list)

입력 : ..two.one...threetwo.. (.은 스페이스로 간주)
출력 : ['', '', 'two', 'one', '', '', 'threetwo', '', '']

참고

https://this-programmer.tistory.com/302

참고문제

Baekjoon 1152.단어의 개수 https://www.acmicpc.net/problem/1152

'프로그래밍 > Python' 카테고리의 다른 글

[Python] 리스트 뒤집기  (0) 2024.04.02
[Python] input()과 readline()의 차이점  (0) 2024.03.25
[Python] 리스트(list)  (0) 2021.04.03
[Python] while문, for문, break, else  (0) 2021.04.03