'How can i keep the dot in a string while removing letters from the alphabet

I have a string: lst = 'sbs1.23444nroen' im using lst2 = ''.join(filter(str.isdigit, lst)) to remove all the letters so the result is: lst2 = '123444' is there any way to include the "." so that the result would be '1.23444' without the letters but keeping the dot?



Solution 1:[1]

A more friendly to the eye solution and extendable if you want to include more characters.

s = 'sbs1.23444nroen'
toKeep = set('0123456789.')
s = ''.join(ch for ch in s if ch in toKeep)
print(s)

Solution 2:[2]

lst2 = ''.join(filter(lambda x: str.isdigit(x) or x=='.', lst))

Solution 3:[3]

An alternative solution would be to use a regular expression, although the set solution is the best so far.

>>> re.findall(r"\d+\.\d*", lst)
['1.23444']

With the added benefit of grabbing other groups of numbers as well:

>>> re.findall(r"\d+\.?\d*", "sbs1.23444nroe631n")
['1.23444', '631']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jeremy
Solution 3 ddejohn