-2

a string is given with alphabets and numbers. for example 1256Ab79.

We have to remove 56 and 7 where ever it occurs from the string.

Input:

1256Ab79

Output:

12Ab9

Input:

a567Eq79

Output:

aEq9

I tried .isdigits() functions but i'm not able to slove that

  • Does this answer your question? [How to replace set or group of characters with string in Python](https://stackoverflow.com/questions/48350607/how-to-replace-set-or-group-of-characters-with-string-in-python) – Kirk Jan 28 '21 at 02:20

3 Answers3

3

You can chain 2 str.replace() together. For this specific and very simple case:

>>> s = '1256Ab79'
>>> s.replace('56', '').replace('7', '')
'12Ab9'
>>> s = 'a567Eq79'
>>> s.replace('56', '').replace('7', '')
'aEq9'

The first replace() replaces any instance of the sub-string '56' with an empty string, effectively removing it. Likewise the second removes '7' from the string. Note that we can chain multiple calls to replace() together because replace() returns the modified string.

If you require more complex replacements, or there are a great many possible target strings, then you could look at re.sub() and dynamically construct the regex pattern from a list of possible target strings.

mhawke
  • 84,695
  • 9
  • 117
  • 138
1

Regular expressions can be used for this purpose:

import re
re.sub(r'\W+', '', your_string)

By Python definition ... '\W == [^a-zA-Z0-9_], this will excludes all numbers, letters and _

Manzurul Hoque Rumi
  • 2,911
  • 4
  • 20
  • 43
TanvirChowdhury
  • 2,498
  • 23
  • 28
0

You could try using re.sub() with the regular expression 56|7

import re

word = '1256Ab79'
re.sub(r'56|7', '', word)
12Ab9
VoidTwo
  • 569
  • 1
  • 7
  • 26