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

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

阅读 6.1k
2 个回答

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)

用match方法,找到第一个match的位置,然后字符串替换就好了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题