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

Python: How do I check if something in a string is right

我是 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,然后检查其中的一些是否正确吗?

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

from math import pi

pianswer = input ("What is pi?")
if str(pi).startswith(pianswer):
    print ("That is correct")
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.")