需求:字符串里面的空格太多,strip()左右空格去除不满足需求
注意:此代码来源Tornado源码
#!/usr/bin/env python # -*- coding: utf-8 -*- import re def squeeze(value: str, replace=" ") -> str: """将所有空格字符序列替换为单个空格.""" return re.sub(r"[x00-x20]+", replace, value).strip() if __name__ == '__main__': s = ' 测 试 ' ret = squeeze(s) print(ret) # 运行结果 # 测 试