Skip to content Skip to sidebar Skip to footer

How To Remove All The Values In A String Except For The Chosen Ones

So my code is value = '123456' I want to remove everything except for 2 and 5. the output will be 25 the program should work even the value is changed for example value = '463312

Solution 1:

Instead of trying to remove every unwanted character, you will be better off to build a whitelist of the characters you want to keep in the result:

>>> value = '123456'
>>> whitelist = set('25')
>>> ''.join([c for c in value if c in whitelist])
'25'

Here is another option where the loop is implicit. We build a mapping to use with str.translate where every character maps to '', unless specified otherwise:

>>> from collections import defaultdict
>>> d = defaultdict(str, str.maketrans('25', '25'))
>>> '123456'.translate(d)
'25'

Solution 2:

In case you are looking for regex solution then you can use re.sub to replace all the characters other than 25 with ''.

import re
x = "463312"
new = re.sub('[^25]+' ,'', x)
x = "463532312"
new = re.sub('[^25]+' ,'', x)

Output: 2, 522


Solution 3:

If you are using Python 2, you can use filter like this:

In [60]: value = "123456"

In [61]: whitelist = set("25")

In [62]: filter(lambda x: x in whitelist, value)
Out[62]: '25'

If you are using Python 3, you would need to "".join() the result of the filter.


Solution 4:

value="23456"
j=""
for k in value:
    if k=='2' or k=='5':
        j=j+k
print (j)

It is the woorking program of what you said, You can give any input to the value, it will always print 25.


Solution 5:

value = "123456"

whitelist = '25'

''.join(set(whitelist) & set(value))
'25'

Post a Comment for "How To Remove All The Values In A String Except For The Chosen Ones"