re.sub on lists - python 3

前端 未结 2 1815
陌清茗
陌清茗 2021-01-06 06:47

I have a list on which I try to remove special chars using a loop. When I\'ve tried to remove those special chars without a loop, it worked. But with a loop didn\'t work, bu

相关标签:
2条回答
  • 2021-01-06 07:19

    Assuming you are trying to keep the stuff inside the brackets, this works:

    import re
    # Case 1 : no sub!
    w = '[ 1,2,3,4 ]'
    
    outer= re.compile("\[(.+)\]")
    m = outer.search(w)
    inner_str = m.group(1)
    print(inner_str)
    
    # Case 2 - no sub!
    x = [ '[1]', '[2]' ]
    
    y = []
    for item in x:
        match = outer.match(item)
        if match:
            y.append(match.group(1))
    
    print(y)
    
    0 讨论(0)
  • 2021-01-06 07:31

    You can do this using a list comprehension, you mean something like this?

    >>> import re
    >>> x = [ '[1]', '[2]' ]
    >>> [re.sub(r'\W', '', i) for i in x]
    ['1', '2']
    

    The token \W matches any non-word character.

    0 讨论(0)
提交回复
热议问题