-1

I'm trying to use str.replace to replace the 5 digit numbers in my string and the following does not work:

print((str.replace(\d\d\d\d\d, "n"))

pchong
  • 1
  • 1
  • that is missing, among other errors, a closing `)` – Thomas Nov 23 '19 at 18:42
  • 3
    Possible duplicate of [Replacing digits with str.replace()](https://stackoverflow.com/questions/19084443/replacing-digits-with-str-replace) – B. Go Nov 23 '19 at 18:43
  • Welcome to Stack Overflow! Check out the [tour]. Your code has at least two syntax errors, but you can [edit] to fix it. – wjandrea Nov 23 '19 at 18:43

1 Answers1

1

str.replace doesn't support regular expressions. For that use re.sub.

import re
s = 'I have 12345 cows'
print(re.sub(r'\d{5}', "n", s))  # -> I have n cows

Breakdown

  • r'...' - Raw string: backslashes are taken literally
  • \d{5} - Equivalent to \d\d\d\d\d. Braces multiply.
wjandrea
  • 28,235
  • 9
  • 60
  • 81