programing

Python에서 공백에 문자열 분할

itsource 2022. 10. 14. 21:47
반응형

Python에서 공백에 문자열 분할

Python과 동등한 제품을 찾고 있습니다.

String str = "many   fancy word \nhello    \thi";
String whiteSpaceRegex = "\\s";
String[] words = str.split(whiteSpaceRegex);

["many", "fancy", "word", "hello", "hi"]

인수 없는 메서드는 공백으로 분할됩니다.

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']
import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)

사용.split()현을 쪼개는 가장 피톤적인 방법이 될 것입니다.

또, 이 기능을 사용하는 경우는,split()공백이 없는 문자열에서는 해당 문자열이 목록으로 반환됩니다.

예:

>>> "ark".split()
['ark']

다른 방법으로는re모듈.띄어쓰기를 하지 않고 모든 단어를 맞추는 역연산을 한다.

>>> import re
>>> s = "many   fancy word \nhello    \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']

위의 regex는 공백이 아닌 하나 이상의 문자와 일치합니다.

언급URL : https://stackoverflow.com/questions/8113782/split-string-on-whitespace-in-python

반응형