python正则替换字符串

re模块sub方法

方法定义:re.sub(pattern, repl, string, count=0, flags=0)

  • pattern : 正则中的模式字符串。
  • repl : 替换的字符串,也可为一个函数。
  • string : 要被查找替换的原始字符串。
  • count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。

如需要替换字符串中的空格和换行符:

import re

text = '\n                                    云南虫谷\n                                '
t = re.sub('\\n(\\s)+', '', text, 0)
print(t)

你可能感兴趣的:(python)