检查字符串是否可以在Python中表示为数字的最佳方法是什么?
我目前拥有的功能是:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Run Code Online (Sandbox Code Playgroud)
这不仅是丑陋而且缓慢,似乎很笨重.但是我没有找到更好的方法,因为调用floatmain函数更糟糕.
有没有办法判断一个字符串是否代表一个整数(例如'3','-17'但不是'3.14'或'asfasfas')没有使用try/except机制?
is_int('3.14') = False
is_int('-7') = True
Run Code Online (Sandbox Code Playgroud) 我在try和except语句中遇到一些问题,我有一个条目小部件,它接受字符串输入,但我有代码,后来将它转换为整数,问题是如果用户输入类似文本的东西,它会抛出这样的错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.2/tkinter/__init__.py", line 1402, in __call__
return self.func(*args)
File "/home/ppppwn3d/workspace/Python/JailBreakBob/JailBreakBob.py", line 157, in buttonclick_gamescreen
entryx = int(e1.get())
ValueError: invalid literal for int() with base 10: 'abc'
Run Code Online (Sandbox Code Playgroud)
所以我想用try和except语句隐藏错误但我现在得到另一条错误消息.
这就是它在代码中的样子.
while pressed == 8 :
try:
entryx = int(e1.get())
entryy = int(e2.get())
except ValueError:
print("text")
answerx = answerlistx[randomimage]
answery = answerlisty[randomimage]
if entryx == answerx and entryy == answery
canvas.delete(images)
randomimage = random.randrange(0,49+1)
scorecounter = scorecounter + 1
game = PhotoImage(file=imagelist[randomimage])
images …Run Code Online (Sandbox Code Playgroud) 我正在尝试制作一个简短的程序,它将返回一个数字的阶乘,这很好.我遇到的唯一问题是如果用户输入非整数值,程序将结束.
num = input("input your number to be factorialised here!: ")
try:
num1 = int(num)
except ValueError:
print("That's not a number!")
if num1 < 0:
print("You can't factorialise a negative number")
elif num1 == 0:
print("the factorial of 0 is 1")
else:
for i in range(1,num1+1):
ans = ans * i
print("the factorial of", num, "is", ans)
Run Code Online (Sandbox Code Playgroud) 使用 NLTK 获取以下内容的唯一词频的代码。
Seq Sentence
1 Let's try to be Good.
2 Being good doesn't make sense.
3 Good is always good.
输出:
{'good':3, 'let':1, 'try':1, 'to':1, 'be':1, 'being':1, 'doesn':1, 't':1, 'make':1, 'sense':1, 'is':1, 'always':1, '.':3, ''':2, 's':1}
我正在编写一个程序,需要检查用户输入是否是十进制(用户输入必须是十进制数),我想知道如何测试变量以查看它是否只包含十进制数。
谢谢,贾维
just need a little help. Starting out doing python, trying to create a high score program and I want to say while score is not equal to an integer then ask user to input score.
For example (this doesn't work)
name = input("Please enter your name: ")
score = None
while score != int(score):
score = input("Enter your score: ")
print("congratz it worked genius")
Run Code Online (Sandbox Code Playgroud)
thanks in advance
我有一个Python脚本,它将十进制数转换为二进制数,这显然使用了他们的输入.
我想让脚本验证输入是一个数字,而不是任何会停止脚本的东西.
我尝试过if/else语句,但我真的不知道如何去做.我曾尝试if decimal.isint():和if decimal.isalpha():,但是当我输入一个字符串,他们只是扔了错误.
print("Welcome to the Decimal to Binary converter!")
while True:
print("Type a decimal number you wish to convert:")
decimal = int(input())
if decimal.isint():
binary = bin(decimal)[2:]
print(binary)
else:
print("Please enter a number.")
Run Code Online (Sandbox Code Playgroud)
如果没有if/else语句,代码就可以正常运行并完成其工作.
我有这个简单的项目要做.这是我到目前为止的代码,它工作得非常好.但如果有人输入字母或未知符号,程序会崩溃.如果输入错误的内容,如何进行此错误验证并显示或打印消息?
def excercise5():
print("Programming Excercise 5")
print("This program calculates the cost of an order.")
pound = eval(input("Enter the weight in pounds: "))
shippingCost = (0.86 * pound) + 1.50
coffee = (10.50 * pound) + shippingCost
if pound == 1:
print(pound,"pound of coffee costs $", coffee)
else:
print(pound,"pounds of coffee costs $", coffee)
print()
excercise5()
Run Code Online (Sandbox Code Playgroud) 这是一个更大的计划的一部分.这是我想要做的.
这是我正在尝试的:
def scan(self, sentence):
self.term = []
for word in sentence.split():
if word in direction:
self.term.append(('direction', word))
elif word in verbs:
self.term.append(('verb', word))
elif word in stop:
self.term.append(('stop', word))
elif word in nouns:
self.term.append(('noun', word))
elif type(int(word)) == 'int':
self.term.append(('number', int(word)))
else:
self.term.append(('error', word))
return self.term
print lexicon.scan('12 1234')
Run Code Online (Sandbox Code Playgroud)
这是一个类中的方法,print语句在外面.我关心和遇到麻烦的部分是这样的:
elif type(int(word)) == int:
self.term.append(('number', int(word)))
Run Code Online (Sandbox Code Playgroud)
它适用于任何自然数[1,无穷大]
编辑:当我尝试扫描时遇到问题('ASDFASDFASDF')
编辑:对于使用逻辑运算符将其标记为重复的人,我发现链接Python 逻辑运算符和那里的答案相当模糊,在找到“或”答案之前必须深入研究它。所以虽然这里的问题是 Python 将 None、False 和 0 一起抛出,很好,但在这里我们想区分前两个和实际的整数或浮点值。除了解释一些基本行为并且没有解决“我们如何以最pythonic的方式处理这种特定情况”之外,那篇文章真的对我的问题没有帮助。//
我在使用 int(... 或 ...) 转换整数时遇到了一些意想不到的行为。我之前没有注意到,因为我通常使用类似的东西:
整数(值或 0)
这总是很好,但是当我将 or 0 更改为另一个值并输入 0 时,我得到了一些我没想到的东西。示例是 int,但浮点数也是如此。
In [88]: int(None or 1)
Out[88]: 1
In [89]: int(2 or 1)
Out[89]: 2
In [90]: int(0 or 1)
Out[90]: 1
In [91]: int(0)
Out[91]: 0
Run Code Online (Sandbox Code Playgroud)
编辑:我希望 [90] 与 [91] 做同样的事情,但显然不是。我的问题是:为什么它会执行这种行为,以及如何以 Pythonic 的方式处理此问题而不必求助于尝试异常。
这是因为它像布尔值一样求值,因此 0 返回 or 值?处理这个问题的常见做法是什么?因为这在我们的程序中是很常见的事情,使用 try except 会创建一些难看的、不太可读的代码......这里使用 python 2.7。
这是我目前获得预期行为的解决方法:
try:
value = int(value)
except (TypeError, ValueError) as e: …Run Code Online (Sandbox Code Playgroud)