繁体   English   中英

如何忽略用户输入中的某些字符串?

[英]How to ignore certain strings from user input?

初学者问题:

如何让我的输入代码忽略某些文本字符串?

你叫什么人? 我是弗雷德

你几岁我是弗雷德

如何忽略“我是”这个词的用户输入?

你几岁我是弗雷德? 我 25 岁

啊,弗雷德,我 25岁还不算老。

在处理整数时如何再次忽略用户输入?

这是我到目前为止的代码:

name = input("What is your name human? ")

while True:
        try:
                age = int(float(input("How old are you " + name + "? ")))

                if age >= 50:
                        print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
                else:
                        print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
                break
        except ValueError:
                print("No, I asked how old you were... ")
                print("Let us try again.")
          

您可以使用.replace('replace what','replace with')来实现这一点。 在这种情况下,您可以使用以下内容:

name = input("What is your name human? ").replace("I'm ","").title()

while True:
    try:
        age = int(input("How old are you " + name + "? ").replace("I'm ",""))

        if age >= 50:
            print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
        else:
            print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
        break
    except ValueError:
            print("No, I asked how old you were... ")
            print("Let us try again.")

同样,您可以使用您认为用户可能输入的词,这是一种方法。

为什么不使用应该从输入中忽略或删除的单词列表,我建议您使用以下解决方案。

toIgnore = ["I'm ", "my name is ", "i am ", "you can call me "]
name = input("What is your name human? ")

for word in toIgnore:
    name = name.replace(word, "")

while True:
    try:
        age = int(float(input("How old are you " + name + "? ")))

        if age >= 50:
            print(str(age) + "! Wow " + name + ", you're older than most of the oldest computers!")
        else:
            print ("Ahh, " + name + ", " + str(age) + " isn't that old.")
            break
    except ValueError:
        print("No, I asked how old you were... ")
        print("Let us try again.")

输出如下

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM