-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
  • 607,720
  • 39
  • 448
  • 563
Sid
  • 552
  • 6
  • 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
  • 21,987
  • 6
  • 62
  • 97
0

Try below,

text = re.sub(' [0-9]{1,} ', ' ', text)
Gokul nath
  • 494
  • 2
  • 8
  • 17
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
  • 53,056
  • 7
  • 34
  • 70