【问题标题】:Python: How do I check if something in a string is rightPython:如何检查字符串中的某些内容是否正确
【发布时间】:2015-09-27 17:23:50
【问题描述】:

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

【问题讨论】:

    标签: python string variables pi


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:
      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.")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-14
        • 2010-11-22
        • 2011-03-31
        • 2017-09-09
        • 2014-09-25
        相关资源
        最近更新 更多