Python:如何检查字符串中的某些内容是否正确

时间:2015-09-27 17:23:51

标签: python string variables pi

我是python的新手,对不起,如果我听起来非常愚蠢

因此,您可以检查其中某些数字是否正确,而不是检查字符串中的每个数字?这是一个例子

pianswer = input ("What is pi?")
if pianswer == "3.14":
print ("That is correct")

因此,如果有人可以做更长版本的pi,而不是做这样的事情:

pianswer = input ("What is pi?")
if pianswer == "3.14":
    print ("That is correct")
elif pianswer == "3.141592":
    print ("That is correct")
elif pianswer == "3.1415":
    print ("That is correct

然后,我可以做一些只知道50位数的pi,然后检查是否有一些是正确的吗?

2 个答案:

答案 0 :(得分:4)

您可以从pi导入math,将其转换为字符串,然后检查它是否以用户的输入开头:

from math import pi

pianswer = input ("What is pi?")
if str(pi).startswith(pianswer):
    print ("That is correct")

答案 1 :(得分:1)

import math

pi = str(math.pi)

answer = input("What is pi? ")

if pi == answer:
    print("You got it right, well, based on how many digits I know.")
elif pi.startswith(answer):
    print("The digits you put in are right, but I know more!")
elif answer.startswith("pi"):
    print("You put in more digits than I know, but the ones I know are right!")
else:
    print("Nope, that's wrong.")