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 '#'
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'
^(\D*) would capture the cat is called<space> part and \d would match the following digit 3. re.sub function will replace all the matched chars with the chars present inside the replacement part. Here the match is the cat is called 3, so this would be replaced by \1=the cat is called , # = #. I think now you get the point.