Skip to main content
 首页 » 编程设计

python之用于删除空格的正则表达式

2025年05月04日24webabcd

def remove_whitespaces(value): 
    "Remove all whitespaces" 
    p = re.compile(r'\s+') 
    return p.sub(' ', value) 

上面的代码去除了标签,但没有从值中去除“所有”空格。

谢谢

请您参考如下方法:

最快的一般方法避开 RE,转而使用字符串的快速、强大 .translate方法:

import string 
identity = string.maketrans('', '') 
 
def remove_whitespace(value): 
  return value.translate(identity, string.whitespace) 

在2.6中,就更简单了,就

  return value.translate(None, string.whitespace) 

请注意,这适用于“普通”Python 2.* 字符串,即字节串——Unicode 的字符串的 .translate 方法有些不同——它需要一个必须是映射的参数ord 值的 Unicode 字符到 Unicode 字符串,或 None 删除。即,利用 dict 的方便 .fromkeys类方法:

nospace = dict.fromkeys(ord(c) for c in string.whitespace) 
 
def unicode_remove_whitespace(value): 
  return value.translate(nospace) 

删除完全相同的一组字符。当然,Unicode 也有更多字符,您可以将其视为空白并希望删除——因此您可能希望根据模块 unicodedata 中的信息构建映射 unicode_nospace ,而不是使用基于模块 string 的这种更简单的方法.