我目前正在创建一个用于denary和denary到二进制转换器的GUI二进制文件。 对于二进制到denary部分的输入,我创建了一个if语句,用于检查输入中除1和0之外的数字,但是它检查错误字符的能力是不可预测的,并且不会产生可靠的结果,或者对我来说,他们似乎不可靠。
如果有人可以建议一种更好的方法来检查字符,或者可以告诉我我的错误,那将非常感激。
BToDInput=input("Enter the Binary string ")
if (("2" or "3" or "4" or "5" or "6" or "7" or "8" or "9") in BToDInput):
print("invalid character")
else:
print("character accepted")
答案 0 :(得分:0)
为了验证二进制字符串的内容,最好使用正则表达式:
#Python regular expression library
import re
#Get as raw input, so we can process as a string later
BToDInput = raw_input("Enter the Binary string ")
#This searches for any character in the string that is not (denoted by the ^) in the range 0 - 1 (deonted by [0-1])
#If the search returns an empty list (None), then we know that the string contains nothing but 1's and 0's
if re.search("[^0-1]", BToDInput) == None:
print("character accepted")
else:
print("invalid character")
如果您要进行更多的字符串处理,请务必阅读Python的正则表达式库:https://docs.python.org/2/library/re.html
我希望这有帮助!