B
♪ check whether the line is a user-builtYou can use it. int in try/except, similar to the response https://ru.stackoverflow.com/q/494591/23044 recommended https://ru.stackoverflow.com/questions/585259/python-3-%d0%9f%d1%80%d0%be%d0%b2%d0%b5%d1%80%d0%ba%d0%b0-%d0%bd%d0%b0-%d1%86%d0%b5%d0%bb%d0%be%d0%b5-%d1%87%d0%b8%d1%81%d0%bb%d0%be#comment781875_585259 Replacement float ♪ int like, https://ru.stackoverflow.com/questions/585259/python-3-%d0%9f%d1%80%d0%be%d0%b2%d0%b5%d1%80%d0%ba%d0%b0-%d0%bd%d0%b0-%d1%86%d0%b5%d0%bb%d0%be%d0%b5-%d1%87%d0%b8%d1%81%d0%bb%d0%be#comment781889_585259 and proposed https://ru.stackoverflow.com/a/585263/23044 clearly showed:def isint(s):
try:
int(s)
return True
except ValueError:
return False
Example:>>> isint('10')
True
>>> isint('a') # не десятичная цифра
False
>>> isint('²') # верхний индекс
False
>>> isint('১') # Bengali (Unicode)
True
This may break if the entry is not a line, for example:>>> isint(0.5) # XXX не работает для float
True
>>> 0.5 .is_integer()
False
>>> from numbers import Integral
>>> isinstance(0.5, Integral)
False
>>> isinstance(123, Integral)
True
>>> isinstance(1., Integral) # XXX float
False
>>> 1..is_integer() # но целое значение
True
>>> from fractions import Fraction
>>> isint(Fraction(1, 2)) # XXX не работает для дробей
True
>>> isinstance(Fraction(1, 2), Integral)
False
>>> isinstance(Fraction(1), Integral) # XXX дробь
False
>>> Fraction(1) == 1 # даже если целое значение
True
See. https://stackoverflow.com/q/21583758/4279 ♪If you want to check that the line transferred contains only decimal numbers and nothing more (e.g., no) '+'♪'-'♪ ' '♪ '\n' symbols in it), https://docs.python.org/3/library/stdtypes.html#str.isdecimal :>>> '123'.isdecimal()
True
>>> '+123'.isdecimal()
False
>>> isint('+123')
True
>>> isint(' 123\n')
True
>>> ' 123\n'.isdecimal()
False
isdecimal() It is possible to use the names of the numerical files in "natural" to sort out (as Windows wire). See. https://stackoverflow.com/q/2545532/4279 ♪If you want. a few. Such numbers can be extracted from the introduction, and regular expression can be used:>>> import re
>>> from datetime import datetime
>>> date_string = '2016-11-01 23:04:05'
>>> datetime(*map(int, re.findall(r'\d+', date_string)))
datetime.datetime(2016, 11, 1, 23, 4, 5)
Last, this is as simple as possible, less stringent (and effective) option for: >>> datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
datetime.datetime(2016, 11, 1, 23, 4, 5)
If you're willing to allow an entire number to be set at random as Pitton's reference code, then tell me. base=0:>>> int('0b1110', 0) # binary ("01")
14
>>> int('0xcafe', 0) # hexadecimal
51966
Details https://docs.python.org/3/library/functions.html#int ♪