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

前端 未结 7 674
悲哀的现实
悲哀的现实 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 11:51
    for each_string in list:
        each_string.lstrip(',./";:') #you can put all kinds of characters that you want to ignore.
    
    0 讨论(0)
  • 2021-01-14 11:52

    strip() when used without parameters strips only spaces. If you want to strip any other character, you need to pass it as a parameter to strip function. In your case you should be doing

    a[i]=a[i].strip(',')
    
    0 讨论(0)
  • 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))]
    
    0 讨论(0)
  • 2021-01-14 12:03

    If you want to remove it only from the begining, try this:

        import re
        s='"gets'
        re.sub(r'("|,,)(.*)',r'\2',s)
    
    0 讨论(0)
  • 2021-01-14 12:09

    To remove punctuation, spaces, numbers from the beginning of each string in a list of strings:

    import string
    
    chars = string.punctuation + string.whitespace + string.digits    
    a[:] = [s.lstrip(chars) for s in a]
    

    Note: it doesn't take into account non-ascii punctuation, whitespace, or digits.

    0 讨论(0)
  • 2021-01-14 12:14

    Pass the characters you want to remove in lstrip and rstrip

    '..foo..'.lstrip('.').rstrip('.') == 'foo'
    
    0 讨论(0)
提交回复
热议问题