Removing Punctuation From Python List Items

后端 未结 5 687
耶瑟儿~
耶瑟儿~ 2020-11-29 08:56

I have a list like

[\'hello\', \'...\', \'h3.a\', \'ds4,\']

this should turn into

[\'hello\', \'h3a\', \'ds4\']

相关标签:
5条回答
  • 2020-11-29 09:07

    Assuming that your initial list is stored in a variable x, you can use this:

    >>> x = [''.join(c for c in s if c not in string.punctuation) for s in x]
    >>> print(x)
    ['hello', '', 'h3a', 'ds4']
    

    To remove the empty strings:

    >>> x = [s for s in x if s]
    >>> print(x)
    ['hello', 'h3a', 'ds4']
    
    0 讨论(0)
  • 2020-11-29 09:18
    import string
    
    print ''.join((x for x in st if x not in string.punctuation))
    

    ps st is the string. for the list is the same...

    [''.join(x for x in par if x not in string.punctuation) for par in alist]
    

    i think works well. look at string.punctuaction:

    >>> print string.punctuation
    !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
    
    0 讨论(0)
  • 2020-11-29 09:22

    Use string.translate:

    >>> import string
    >>> test_case = ['hello', '...', 'h3.a', 'ds4,']
    >>> [s.translate(None, string.punctuation) for s in test_case]
    ['hello', '', 'h3a', 'ds4']
    

    For the documentation of translate, see http://docs.python.org/library/string.html

    0 讨论(0)
  • 2020-11-29 09:22

    To make a new list:

    [re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings]
    
    0 讨论(0)
  • 2020-11-29 09:27

    In python 3+ use this instead:

    import string
    s = s.translate(str.maketrans('','',string.punctuation))
    
    0 讨论(0)
提交回复
热议问题