Reputation: 484
import re
sentence = "the cat is called 303worldDomination"
print re.sub(r'\d', r'#', sentence)
However, this substitutes all the digits in the string with '#'
I only want the first digit in the string to be substituted by '#'
Upvotes: 3
Views: 2754
Reputation: 174706
Use anchor and capturing group.
re.sub(r'^(\D*)\d', r'\1#', sentence)
^
asserts that we are at the start.
(\D*)
would capture all the non-digit characters which are present at the start. So group index 1 contains all the non-digit characters present at the start.
So this regex will match upto the first digit character. In this, all the chars except the first digit was captured. We could refer those captured characters by specifying it's index number in the replacement part.
r'\1#'
will replace all the matched chars with the chars present inside group index 1 + #
symbol.
Example:
>>> sentence = "the cat is called 303worldDomination"
>>> re.sub(r'^(\D*)\d', r'\1#', sentence)
'the cat is called #03worldDomination'
Upvotes: 3
Reputation: 176820
You can use the count
argument to specify that just one substitution (i.e. the first match) should be made:
>>> re.sub(r'\d', r'#', sentence, count=1)
'the cat is called #03worldDomination'
Upvotes: 12