Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def is_number(s):
- try:
- float(s)
- return True
- except ValueError:
- return False
- >>> a = "03523"
- >>> a.isdigit()
- True
- >>> b = "963spam"
- >>> b.isdigit()
- False
- >>> float('NaN')
- nan
- '3.14'.replace('.','',1).isdigit()
- '3.14.5'.replace('.','',1).isdigit()
- def is_number(s):
- try:
- complex(s) # for int, long, float and complex
- except ValueError:
- return False
- return True
- def is_number(s):
- try:
- float(s) # for int, long and float
- except ValueError:
- try:
- complex(s) # for complex
- except ValueError:
- return False
- return True
- def parse(string):
- try:
- return float(string)
- except Exception:
- throw TypeError
- def try_parse(string, fail=None):
- try:
- return float(string)
- except Exception:
- return fail;
- def monkey_patch():
- if(!hasattr(float, 'parse')):
- float.parse = parse
- if(!hasattr(float, 'try_parse')):
- float.try_parse = try_parse
- float.parse('giggity') // throws TypeException
- float.parse('54.3') // returns the scalar value 54.3
- float.tryParse('twank') // returns None
- float.tryParse('32.2') // returns the scalar value 32.2
- from __future__ import print_function
- import timeit
- prep_base = '''
- x = 'invalid'
- y = '5402'
- z = '4.754e3'
- '''
- prep_try_method = '''
- def is_number_try(val):
- try:
- float(val)
- return True
- except ValueError:
- return False
- '''
- prep_re_method = '''
- import re
- float_match = re.compile(r'[-+]?d*.?d+(?:[eE][-+]?d+)?$').match
- def is_number_re(val):
- return bool(float_match(val))
- '''
- fn_method = '''
- from fastnumbers import isfloat
- '''
- print('Try with non-number strings', timeit.timeit('is_number_try(x)',
- prep_base + prep_try_method), 'seconds')
- print('Try with integer strings', timeit.timeit('is_number_try(y)',
- prep_base + prep_try_method), 'seconds')
- print('Try with float strings', timeit.timeit('is_number_try(z)',
- prep_base + prep_try_method), 'seconds')
- print()
- print('Regex with non-number strings', timeit.timeit('is_number_re(x)',
- prep_base + prep_re_method), 'seconds')
- print('Regex with integer strings', timeit.timeit('is_number_re(y)',
- prep_base + prep_re_method), 'seconds')
- print('Regex with float strings', timeit.timeit('is_number_re(z)',
- prep_base + prep_re_method), 'seconds')
- print()
- print('fastnumbers with non-number strings', timeit.timeit('isfloat(x)',
- prep_base + 'from fastnumbers import isfloat'), 'seconds')
- print('fastnumbers with integer strings', timeit.timeit('isfloat(y)',
- prep_base + 'from fastnumbers import isfloat'), 'seconds')
- print('fastnumbers with float strings', timeit.timeit('isfloat(z)',
- prep_base + 'from fastnumbers import isfloat'), 'seconds')
- print()
- Try with non-number strings 2.39108395576 seconds
- Try with integer strings 0.375686168671 seconds
- Try with float strings 0.369210958481 seconds
- Regex with non-number strings 0.748660802841 seconds
- Regex with integer strings 1.02021503448 seconds
- Regex with float strings 1.08564686775 seconds
- fastnumbers with non-number strings 0.174362897873 seconds
- fastnumbers with integer strings 0.179651021957 seconds
- fastnumbers with float strings 0.20222902298 seconds
- >>> "1221323".isdigit()
- True
- >>> "12.34".isdigit()
- False
- >>> "12.34".replace('.','',1).isdigit()
- True
- >>> "12.3.4".replace('.','',1).isdigit()
- False
- >>> '-12'.lstrip('-')
- '12'
- >>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
- True
- >>> '.-234'.lstrip('-').replace('.','',1).isdigit()
- False
- >>> s = u"345"
- >>> s.isnumeric()
- True
- >>> s = "345"
- >>> u = unicode(s)
- >>> u.isnumeric()
- True
- if str.isdigit():
- returns TRUE or FALSE
- def is_number(s):
- try:
- n=str(float(s))
- if n == "nan" or n=="inf" or n=="-inf" : return False
- except ValueError:
- try:
- complex(s) # for complex
- except ValueError:
- return False
- return True
- import time
- import re
- check_regexp = re.compile("^d*.?d*$")
- check_replace = lambda x: x.replace('.','',1).isdigit()
- numbers = [str(float(x) / 100) for x in xrange(10000000)]
- def is_number(s):
- try:
- float(s)
- return True
- except ValueError:
- return False
- start = time.time()
- b = [is_number(x) for x in numbers]
- print time.time() - start # returns 4.10500001907
- start = time.time()
- b = [check_regexp.match(x) for x in numbers]
- print time.time() - start # returns 5.41799998283
- start = time.time()
- b = [check_replace(x) for x in numbers]
- print time.time() - start # returns 4.5110001564
- try:
- myvar.append( float(string_to_check) )
- except:
- continue
- def is_number_tryexcept(s):
- """ Returns True is string is a number. """
- try:
- float(s)
- return True
- except ValueError:
- return False
- import re
- def is_number_regex(s):
- """ Returns True is string is a number. """
- if re.match("^d+?.d+?$", s) is None:
- return s.isdigit()
- return True
- def is_number_repl_isdigit(s):
- """ Returns True is string is a number. """
- return s.replace('.','',1).isdigit()
- funcs = [
- is_number_tryexcept,
- is_number_regex,
- is_number_repl_isdigit
- ]
- a_float = '.1234'
- print('Float notation ".1234" is not supported by:')
- for f in funcs:
- if not f(a_float):
- print('t -', f.__name__)
- scientific1 = '1.000000e+50'
- scientific2 = '1e50'
- print('Scientific notation "1.000000e+50" is not supported by:')
- for f in funcs:
- if not f(scientific1):
- print('t -', f.__name__)
- print('Scientific notation "1e50" is not supported by:')
- for f in funcs:
- if not f(scientific2):
- print('t -', f.__name__)
- def str_to_type (s):
- """ Get possible cast type for a string
- Parameters
- ----------
- s : string
- Returns
- -------
- float,int,str,bool : type
- Depending on what it can be cast to
- """
- try:
- f = float(s)
- if "." not in s:
- return int
- return float
- except ValueError:
- value = s.upper()
- if value == "TRUE" or value == "FALSE":
- return bool
- return type(s)
- str_to_type("true") # bool
- str_to_type("6.0") # float
- str_to_type("6") # int
- str_to_type("6abc") # str
- str_to_type(u"6abc") # unicode
- s = "6.0"
- type_ = str_to_type(s) # float
- f = type_(s)
- def string_or_number(s):
- try:
- z = int(s)
- return z
- except ValueError:
- try:
- z = float(s)
- return z
- except ValueError:
- return s
- def is_number(var):
- try:
- if var == int(var):
- return True
- except Exception:
- return False
- def isFloat(s):
- realFloat = 0.1
- if type(s) == type(realFloat):
- return True
- else:
- return False
- False # s = 5
- True # s = 1.2345
- import sys
- def fix_quotes(s):
- try:
- float(s)
- return s
- except ValueError:
- return '"{0}"'.format(s)
- for line in sys.stdin:
- input = line.split()
- print input[0], '<- c(', ','.join(fix_quotes(c) for c in input[1:]), ')'
- number = raw_input("Enter a number: ")
- if re.match(r'^d+$', number):
- print "It's integer"
- print int(number)
- elif re.match(r'^d+.d+$', number):
- print "It's float"
- print float(number)
- else:
- print("Please enter a number")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement