Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 views
in Technique[技术] by (71.8m points)

How to remove a number from alphanumeric string in python

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...