Replace matches and count how many substitutions occurred.
How It Works
re.subn() works like sub() but returns (new_string, number_of_substitutions). This is useful for logging how many values changed without scanning the output a second time.
Step-by-Step Example
import re
clean_text, changes = re.subn(r'\s+', ' ', 'too many spaces')
print(clean_text)
print(changes)
Understanding the Example
- The expression "re.subn(r'\\s+', ' ', 'too many spaces')" supplies the value stored as 'clean_text, changes'. This value is then used or checked by the later statements.
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
too many spaces
2
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
The count option limits replacements, and subn reports actual replacements made.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Treating the return value as a plain string instead of a two-item tuple.
- Normalize repeated whitespace and report the number of changed spans.
Key Takeaways
- Replace matches and count how many substitutions occurred.
- re.subn() works like sub() but returns (new_string, number_of_substitutions).
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.