简体   繁体   中英

Using strip() method and punctuation in Python

I've been trying to solve this problem for a few hours now and can't come with the right solution, this is the question:

Write a loop that creates a new word list, using a string method to strip the words from the list created in Problem 3 of all leading and trailing punctuation. Hint: the string library, which is imported above, contains a constant named punctuation. Three lines of code.

Here is my code:

    import string

    def litCricFriend(wordList, text):
        theList = text.lower().replace('-', ' ').split()   #problem 3

        #problem below
        for word in theList:
            word.strip(string.punctuation)
            return theList

You've got a couple bits in your code that... well, I'm not really sure why they're there, to be honest, haha. Let's work through this together!

I'm assuming you have been given some text: text = "My hovercraft is full of eels!" . Let's split this into words, make the words lowercase, and remove all punctuation. We know we need string.punctuation and str.split() , and you've also figured out that str.replace() is useful. So let's use these and get our result!

import string

def remove_punctuation(text):
    # First, let's remove the punctuation.
    # We do this by looping through each punctuation mark in the
    # `string.punctuation` list, and then replacing that mark with
    # the empty string and re-assigning that to the same variable.
    for punc in string.punctuation:
        text = text.replace(punc, '')

    # Now our text is all de-punctuated! So let's make a list of
    # the words, all lowercased, and return it in one go:
    return text.lower().split()

Looks to me like the function is only three lines, which is what you said you wanted!


For the advanced reader, you could also use functools and do it in one line (I split it into two for readability, but it's still "one line"):

import string
import functools

def remove_punctuation(text):
    return functools.reduce(lambda newtext, punc: newtext.replace(punc, ''),
        punctuation, text).lower().split()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM