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"
the output will be 2
I tried to use remove()
and replace()
function. But it didn't work.
Doing it on python 3.6.2
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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With