Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

question from:https://stackoverflow.com/questions/65930103/how-to-remove-a-number-from-alphanumeric-string-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
56 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...