Removing Punctuation From Python List Items

后端 未结 5 710
耶瑟儿~
耶瑟儿~ 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']
    

提交回复
热议问题