-3

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

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

import re

word = '1256Ab79'
re.sub(r'56|7', '', word)
12Ab9

Comments

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 _

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.