如何验证某些二进制输入以确保只有1和0,而不是字母或其他整数?
$('#roomOptions #select1').change(function () {
var total = 0;
$('#roomOptions #select1').each(function () {
total += parseInt($(this).val());
});
$('#roomOptions #roomOptions_total').html(total);
$.ajax({
url: getrooms.php,
type: 'POST',
data: {
"total": total
}
});
});
到目前为止,我只能让我的函数不接受除1或0之外的整数,但它不会让我输入1和0的组合。
整个代码:
user_bin = (input('\nPlease enter binary number: '))
user_bin_list = list(user_bin)
while int(user_bin) < 0 or int(user_bin) > 1:
print('Please make sure your number contains digits 0-1 only.')
user_bin = (input('\nPlease enter binary number: '))
答案 0 :(得分:1)
使用int
构造函数的second parameter(基础):
while True:
user_bin_inp = raw_input('\nPlease enter a binary number: ')
try:
user_bin = int(user_bin_inp, 2)
except ValueError:
print("{!r} is not a valid binary integer.".format(user_bin_inp))
continue
break
答案 1 :(得分:1)
通常,验证用户输入的最简单方法是:
这与Python的"easier to ask forgiveness than permission"风格一致。在这种情况下,您期望输入可以解释为二进制:
while True:
try:
user_bin = int(input('\nPlease enter binary number: '), 2)
except ValueError:
print('Please make sure your number contains digits 0-1 only.')
else:
break