Использование isdigit для поплавков? - PullRequest
21 голосов
/ 09 ноября 2010
a = raw_input('How much is 1 share in that company? ')

while not a.isdigit():
    print("You need to write a number!\n")
    a = raw_input('How much is 1 share in that company? ')

Это работает, только если пользователь вводит integer, но я хочу, чтобы оно работало, даже если они вводят float, но не при вводе string.

Таким образом, пользователь должен иметь возможность ввести 9 и 9.2, но не abc.

Как мне это сделать?

Ответы [ 7 ]

34 голосов
/ 09 ноября 2010

EAFP

try:
    x = float(a)
except ValueError:
    print("You must enter a number")
11 голосов
/ 04 октября 2011

Существующие ответы верны в том смысле, что более Pythonic путь обычно к try...except (т.е. EAFP).

Однако, если вы действительно хотите выполнить проверку, вы можете удалить ровно 1 десятичную точку перед использованием isdigit().

>>> "124".replace(".", "", 1).isdigit()
True
>>> "12.4".replace(".", "", 1).isdigit()
True
>>> "12..4".replace(".", "", 1).isdigit()
False
>>> "192.168.1.1".replace(".", "", 1).isdigit()
False

Обратите внимание, что это не относится к плавающим предметам, однако отличается от целых. Вы можете добавить эту проверку, если она вам действительно нужна.

11 голосов
/ 09 ноября 2010

Используйте регулярные выражения.

import re

p = re.compile('\d+(\.\d+)?')

a = raw_input('How much is 1 share in that company? ')

while p.match(a) == None:
    print "You need to write a number!\n"
    a = raw_input('How much is 1 share in that company? ')
6 голосов
/ 21 сентября 2017

Опираясь на ответ dan04:

def isDigit(x):
    try:
        float(x)
        return True
    except ValueError:
        return False

использование:

isDigit(3)     # True
isDigit(3.1)   # True
isDigit("3")   # True
isDigit("3.1") # True
isDigit("hi")  # False
3 голосов
/ 19 мая 2018
import re

string1 = "0.5"
string2 = "0.5a"
string3 = "a0.5"
string4 = "a0.5a"

p = re.compile(r'\d+(\.\d+)?$')

if p.match(string1):
    print(string1 + " float or int")
else:
    print(string1 + " not float or int")

if p.match(string2):
    print(string2 + " float or int")
else:
    print(string2 + " not float or int")

if p.match(string3):
    print(string3 + " float or int")
else:
    print(string3 + " not float or int")

if p.match(string4):
    print(string4 + " float or int")
else:
    print(string4 + " not float or int")

output:
0.5 float or int
0.5a not float or int
a0.5 not float or int
a0.5a not float or int
3 голосов
/ 10 ноября 2010

Я думаю, что @ dan04 имеет правильный подход (EAFP), но, к сожалению, реальный мир часто является особым случаем, и для управления вещами действительно необходим какой-то дополнительный код, поэтому ниже приведен более сложный, но и немного более прагматичный (и реалистично):

import sys

while True:
    try:
        a = raw_input('How much is 1 share in that company? ')
        x = float(a)
        # validity check(s)
        if x < 0: raise ValueError('share price must be positive')
    except ValueError, e:
        print("ValueError: '{}'".format(e))
        print("Please try entering it again...")
    except KeyboardInterrupt:
        sys.exit("\n<terminated by user>")
    except:
        exc_value = sys.exc_info()[1]
        exc_class = exc_value.__class__.__name__
        print("{} exception: '{}'".format(exc_class, exc_value))
        sys.exit("<fatal error encountered>")
    else:
        break  # no exceptions occurred, terminate loop

print("Share price entered: {}".format(x))

Пример использования:

> python numeric_input.py
How much is 1 share in that company? abc
ValueError: 'could not convert string to float: abc'
Please try entering it again...
How much is 1 share in that company? -1
ValueError: 'share price must be positive'
Please try entering it again...
How much is 1 share in that company? 9
Share price entered: 9.0

> python numeric_input.py
How much is 1 share in that company? 9.2
Share price entered: 9.2
2 голосов
/ 21 мая 2015
s = '12.32'
if s.replace('.', '').replace('-', '').isdigit():
    print(float(s))

Обратите внимание, что это будет работать и для отрицательных float с.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...