split string by arbitrary number of white spaces

后端 未结 6 1327
夕颜
夕颜 2021-01-17 11:07

I\'m trying to find the most pythonic way to split a string like

\"some words in a string\"

into single words. string.split(\' \')

6条回答
  •  旧时难觅i
    2021-01-17 11:33

    Use string.split() without an argument or re.split(r'\s+', string) instead:

    >>> s = 'some words in a string   with  spaces'
    >>> s.split()
    ['some', 'words', 'in', 'a', 'string', 'with', 'spaces']
    >>> import re; re.split(r'\s+', s)
    ['some', 'words', 'in', 'a', 'string', 'with', 'spaces']
    

    From the docs:

    If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

提交回复
热议问题