Michael Barber's answer will be better for speed, as there is no unnecessary logic. If for some reason you find that you need a more detailed evaluation, you can use the standard regex module of the Python standard library. This will help you if, for example, you decide that you want to get the number as you described, but with additional criteria that you want to overlay.
import re mystring = '.0323asdffa' def find_number_with_or_without_decimal(mystring): return re.findall(r"^\.?\d+", mystring) In [1]: find_number_with_or_without_decimal(mystring) Out[1]: ['.0323']
The regular expression says: "find something starting with one decimal place (" ^ "means only at the beginning of the line, and"? "Means up to one, decimal escapes with" \ "so that it won 'has its own special meaning of regular expression "any character") and has any number of digits. Good luck with Python!
source share