Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all the values in a string except for the chosen ones [duplicate]

Tags:

python

string

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

like image 592
dipte Avatar asked Sep 17 '17 03:09

dipte


2 Answers

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'
like image 78
wim Avatar answered Oct 20 '22 00:10

wim


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

like image 36
Bharath Avatar answered Oct 19 '22 23:10

Bharath