python中re.sub使用

先看帮助文档:

Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

基本意思就是从最左面替换匹配的正则表达式, 如果repl是字符串则替换成对应的字符串, 如果是可调用的, 将传一个match对象到里面, 需要返回一个string替换匹配的表达式

举下面一个例子:

# -*- coding: utf-8 -*-
import re

s = u'1990年3月27日'

def replace_digit(m):
    ss = u'〇一二三四五六七八九'
    index = int(m.group())
    return ss[index]

result = re.sub(u'\d', replace_digit, s, count=4)

print(result)

输出结果:

一九九〇年3月27日
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • re模块手册 本模块提供了和Perl里的正则表达式类似的功能,不关是正则表达式本身还是被搜索的字符串,都可以...
    喜欢吃栗子阅读 4,163评论 0 13
  • re模块 开始使用re Python通过re模块提供对正则表达式的支持。使用re的一般步骤是先将正则表达式的字符串...
    Alex陌阅读 1,377评论 0 0
  • 本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达式标准库的完整介绍及使用示例...
    Python程序媛阅读 1,436评论 0 22
  • 使用 Python 模块 re 实现解析小工具 孙 翎, 贺 皓, 和 张 晗 2011 年 4 月 12 日发布...
    种花家LY阅读 3,802评论 0 21
  • 蓑衣客在金陵城里面呆了好几天,身上的盘缠已经所剩无几了,他的脚印已经踏遍了金陵的大街小巷,脚下的草鞋已经残破不堪,...
    a48927c4b670阅读 530评论 0 5

友情链接更多精彩内容