代码之家  ›  专栏  ›  技术社区  ›  Melvin

使用正则表达式[duplicate]从字符串中删除字符

  •  1
  • Melvin  · 技术社区  · 9 年前

    为此,我有:

    punctuations = list(string.punctuation)
    

    其中包含必须从字符串中删除的所有字符。我试图用python中的正则表达式来解决这个问题,有没有关于如何继续使用正则表达式的建议?

    import string
    punctuations = list(string.punctuation)
    test = "0000.1111"
    for i, char in enumerate(test): 
        if char in punctuations:
           test = test[:i] + test[i+ 1:]
    
    1 回复  |  直到 9 年前
        1
  •  3
  •   randomir    9 年前

    re.sub

    >>> re.sub('\W', '', '0-001')
    '0001'
    

    注意 \W 将匹配任何非Unicode文字字符。这与 \w .对于ASCII字符串,它等效于 [^a-zA-Z0-9_] .