How to replace the first occurrence of a regular expression in Python?

前端 未结 2 1831
逝去的感伤
逝去的感伤 2020-11-29 06:08

I want to replace just the first occurrence of a regular expression in a string. Is there a convenient way to do this?

相关标签:
2条回答
  • 2020-11-29 06:44

    Specify the count argument in re.sub(pattern, repl, string[, count, flags])

    The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced.

    0 讨论(0)
  • 2020-11-29 07:09

    re.sub() has a count parameter that indicates how many substitutions to perform. You can just set that to 1:

    >>> s = "foo foo foofoo foo"
    >>> re.sub("foo", "bar", s, 1)
    'bar foo foofoo foo'
    >>> s = "baz baz foo baz foo baz"
    >>> re.sub("foo", "bar", s, 1)
    'baz baz bar baz foo baz'
    

    Edit: And a version with a compiled SRE object:

    >>> s = "baz baz foo baz foo baz"
    >>> r = re.compile("foo")
    >>> r.sub("bar", s, 1)
    'baz baz bar baz foo baz'
    
    0 讨论(0)
提交回复
热议问题