Splitting strings in Python without split()

后端 未结 8 717
醉话见心
醉话见心 2021-01-17 03:59

What are other ways to split a string without using the split() method? For example, how could [\'This is a Sentence\'] be split into [\'This\', \'is\', \'a\', \'Sentence\']

8条回答
  •  礼貌的吻别
    2021-01-17 04:35

    You can use regular expressions if you want:

    >>> import re
    >>> s = 'This is a Sentence'
    >>> re.findall(r'\S+', s)
    ['This', 'is', 'a', 'Sentence']
    

    The \S represents any character that isn't whitespace, and the + says to find one or more of those characters in a row. re.findall will create a list of all strings that match that pattern.

    But, really, s.split() is the best way to do it.

提交回复
热议问题