How to split a string into a list?

后端 未结 9 2461
执念已碎
执念已碎 2020-11-21 04:32

I want my Python function to split a sentence (input) and store each word in a list. My current code splits the sentence, but does not store the words as a list. How do I do

9条回答
  •  别那么骄傲
    2020-11-21 05:15

    How about this algorithm? Split text on whitespace, then trim punctuation. This carefully removes punctuation from the edge of words, without harming apostrophes inside words such as we're.

    >>> text
    "'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'"
    
    >>> text.split()
    ["'Oh,", 'you', "can't", 'help', "that,'", 'said', 'the', 'Cat:', "'we're", 'all', 'mad', 'here.', "I'm", 'mad.', "You're", "mad.'"]
    
    >>> import string
    >>> [word.strip(string.punctuation) for word in text.split()]
    ['Oh', 'you', "can't", 'help', 'that', 'said', 'the', 'Cat', "we're", 'all', 'mad', 'here', "I'm", 'mad', "You're", 'mad']
    

提交回复
热议问题