Awesome_girl
Awesome_girl

Reputation: 484

Change first digit in a string to '#' using regex in python

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

Answers (2)

Avinash Raj
Avinash Raj

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

Alex Riley
Alex Riley

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

Related Questions