-1

I am processing string like

This is python3 and learning it takes 100 hours

I want to remove only digits like 100 but want to keep digits when it is part of anything like python3.

I am trying the regex

text = re.sub('[0-9]', '', text)

but it is not working as expected. Help is appreciated.

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Sid
  • 552
  • 5
  • 21
  • You may now think about accepting an answer or comment one to get details ;) to reward those who spent time for you ;) – azro Mar 20 '20 at 08:44

3 Answers3

1

You can just add a space to both sides of your regex, and then have a single space as the replacement. Remember to also a + to match one or more digits:

import re

text = 'This is python3 and learning it takes 100 hours'
text = re.sub(r' [0-9]+ ', ' ', text)
print(text)

Output:

This is python3 and learning it takes hours
ruohola
  • 19,113
  • 6
  • 51
  • 82
0

Try below,

text = re.sub(' [0-9]{1,} ', ' ', text)
Gokul nath
  • 474
  • 1
  • 8
  • 15
0

You can use \b word boundary (class \d is for [0-9]) :

def clean(value):
    return re.sub(r"\b\d+\b", "", value)

if __name__ == "__main__":
    print(clean("This is python3 and learning it takes 100 hours"))  # This is python3 and learning it takes  hours

Regex demo

azro
  • 47,041
  • 7
  • 30
  • 65