split string by arbitrary number of white spaces

后端 未结 6 1283
夕颜
夕颜 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条回答
  • 2021-01-17 11:18

    Just use my_str.split() without ' '.


    More, you can also indicate how many splits to perform by specifying the second parameter:

    >>> ' 1 2 3 4  '.split(None, 2)
    ['1', '2', '3 4  ']
    >>> ' 1 2 3 4  '.split(None, 1)
    ['1', '2 3 4  ']
    
    0 讨论(0)
  • 2021-01-17 11:19

    The most Pythonic and correct ways is to just not specify any delimiter:

    "some words in a string".split()
    
    # => ['some', 'words', 'in', 'a', 'string']
    

    Also read: How can I split by 1 or more occurrences of a delimiter in Python?

    0 讨论(0)
  • 2021-01-17 11:27

    How about:

    re.split(r'\s+',string)
    

    \s is short for any whitespace. So \s+ is a contiguous whitespace.

    0 讨论(0)
  • 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 [].

    0 讨论(0)
  • 2021-01-17 11:38
    >>> a = "some words in a string"
    >>> a.split(" ")
    ['some', 'words', 'in', 'a', 'string']
    

    split parameter is not included in the result, so i guess theres something more about your string. otherwise, it should work

    if you have more than one whitespace just use split() without parameters

    >>> a = "some words in a string     "
    >>> a.split()
    ['some', 'words', 'in', 'a', 'string']
    >>> a.split(" ")
    ['some', 'words', 'in', 'a', 'string', '', '', '', '', '']
    

    or it will just split a by single whitespaces

    0 讨论(0)
  • 2021-01-17 11:41
    text = "".join([w and w+" " for w in text.split(" ")])
    

    converts large spaces into single spaces

    0 讨论(0)
提交回复
热议问题