Keywords: Python | string replacement | first occurrence
Abstract: This article explains how to use Python's string.replace() function to replace only the first occurrence of a substring. By setting the maxreplace parameter to 1, you can precisely control the number of replacements, avoiding unnecessary global replacements.
Introduction
In Python, replacing the first occurrence of a substring within a string is a common task. This article focuses on an efficient method using the built-in string.replace() function.
Using string.replace() with maxreplace
The string.replace(s, old, new[, maxreplace]) function returns a copy of string s with all occurrences of substring old replaced by new. The optional maxreplace parameter allows limiting the number of replacements. By setting maxreplace=1, only the first occurrence is replaced.
Code Example
Here is an example to demonstrate the usage:
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'In this code, the first occurrence of 'TEST' is replaced with '?', while the second remains unchanged.
Conclusion
Using string.replace() with maxreplace=1 provides a straightforward and efficient way to replace only the first occurrence of a string in Python.