Removing numbers mixed with letters from a string

Suppose I have a line, for example:

string = 'This string 22 is not yet perfect1234 and 123pretty but it can be.'

I want to delete all numbers , which are mixed with words such as 'perfect1234'and '123pretty', but not '22' of my line and get the output as follows:

string = 'This string 22 is not yet perfect and pretty but it can be.'

Is there a way to do this in Python using regex or any other method? Any help would be greatly appreciated. Thank!

-5
source share
5 answers
s = 'This string 22 is not yet perfect1234 and 123pretty but it can be.'

new_s = ""
for word in s.split(' '):
    if any(char.isdigit() for char in word) and any(c.isalpha() for c in word):
        new_s += ''.join([i for i in word if not i.isdigit()])
    else:
        new_s += word
    new_s += ' '

And as a result:

'This string 22 is not yet perfect and pretty but it can be.'
+3
source

If you want to save numbers that are on their own (not part of a word with alpha characters in it), this regular expression will do the job (but there is probably a way to make it easier):

import re
pattern = re.compile(r"\d*([^\d\W]+)\d*")
s = "This string is not yet perfect1234 and 123pretty but it can be. 45 is just a number."
pattern.sub(r"\1", s)
'This string is not yet perfect and pretty but it can be. 45 is just a number.'

45 , .

+2
import re
re.sub(r'\d+', '', string)
+1

In the code below, each character for a digit is checked. If it is not a number, it adds a character to the end of the corrected line.

string = 'This string is not yet perfect1234 and 123pretty but it can be.'

CorrectedString = ""
for characters in string:
    if characters.isdigit():
        continue
    CorrectedString += characters
0
source

You can try this by simply combining the function and also not import anything

str_var='This string is not yet perfect1234 and 123pretty but it can be.'

str_var = ''.join(x for x in str_var if not x.isdigit())
print str_var

output:

'This string is not yet perfect and pretty but it can be.'
0
source

Source: https://habr.com/ru/post/1689323/


All Articles