Lessons · Regex · replacing only the first few
Only the first few, and how many there were
count caps how many are replaced, from the left; subn hands back the result and the number together.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
'Did anything change' is part of the answer often enough that computing it twice is a habit worth dropping.
How to think about it
If you want one, say count=1. If you want to know how many, use subn rather than comparing the new string to the old one.
Worked example
re.sub(r'a', 'X', 'banana', count=1)The first one only.
re.sub(r'a', 'X', 'banana')The default is every one.
re.subn(r'a', 'X', 'banana')The same work, with the count that was already known.
Your turn
Replace only the first 'a'.
re.sub(r'a', 'X', 'banana', =1)
Test a pattern against real text
The trap
The default count is 0 and it means 'no limit', not 'none'. A zero that means everything catches people out.
Practise replacing only the first few on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.