3
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 '#'

0

2 Answers 2

12

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'
Sign up to request clarification or add additional context in comments.

Comments

3

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'

5 Comments

hmm?? what do you mean by the above comment?
^ means first (not sure what that means) * means 0 or more occurrences of the pattern to its left. \d means digit. \D probably also means digit. \1 means group 1 (which i'm not sure what it means). all together, (r'^(\D*)\d' and r'\1#', what do they mean exactly?
so you are saying with the first r'^(\D*)\d' you captured all the characters that are not digits at the start of the sentence, excluding the first digit. so group 1 equals "the cat is called ", then you are searching for \d in group1 and replacing it with '#' ? which doesn't make any sense. I know i'm understanding something wrong here.
^(\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.
I'm so sorry I understand you first sentence, and i don't understand the rest. First why is that 'D' capital in r'^(\D*)\d'. Also I don't understand why adding '\d' to '(^(\D*)' only filters out one digit. just '\d' without (^\D*) filters all digits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.