Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...