python正则表达式如何仅替换一处匹配?

查看:154
本文介绍了python正则表达式如何仅替换一处匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

基于python3
假如说一个字符串中有多处匹配,想要让用户一个一个输入想要替换的东西,但是我知道的sub()方法一下就会把所有的匹配全换完...
所有就想问一下大佬们有没有什么办法实现只替换一处的那种方法...
先谢谢大佬们回答我的弱智问题了哈哈哈

解决方案

re.sub本身就支持指定替换次数, 它的定义是:

sub(pattern, repl, string, count=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.

所以你可以试下

#!/usr/bin/env python
# coding: utf8

import re

test = 'aaaa'
print re.sub('a', 'X', test, 1)

这篇关于python正则表达式如何仅替换一处匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆