简体   繁体   中英

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?

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)
lst2 = ''.join(filter(lambda x: str.isdigit(x) or x=='.', lst))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM