How can we strip punctuation at the start of a string using Python?

前端 未结 7 683
悲哀的现实
悲哀的现实 2021-01-14 11:43

I want to strip all kinds of punctuation at the start of the string using Python. My list contains strings and some of them starting with some kind of punct

7条回答
  •  遥遥无期
    2021-01-14 12:00

    Assuming you want to remove all punctuation regardless of where it occurs in a list containing strings (which may contain multiple words), this should work:

    test1 = ",,gets"
    test2 = ",,gets,,"
    test3 = ",,this is a sentence and it has commas, and many other punctuations!!"
    test4 = [" ", "junk1", ",,gets", "simple", 90234, "234"]
    test5 = "word1 word2 word3 word4 902344"
    
    import string
    
    remove_l = string.punctuation + " " + "1234567890"
    
    for t in [test1, test2, test3, test4, test5]:
        if isinstance(t, str):
            print " ".join([x.strip(remove_l) for x in t.split()])
        else:
            print [x.strip(remove_l) for x in t \
                   if isinstance(x, str) and len(x.strip(remove_l))]
    

提交回复
热议问题