简体   繁体   中英

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

You can use the count argument to specify that just one substitution (ie the first match) should be made:

>>> re.sub(r'\d', r'#', sentence, count=1)
'the cat is called #03worldDomination'

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM