Home > OS >  How can i keep the dot in a string while removing letters from the alphabet
How can i keep the dot in a string while removing letters from the alphabet

Time:04-24

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?

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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']
  • Related