Home > Software engineering >  How to ignore certain strings from user input?
How to ignore certain strings from user input?

Time:11-10

Beginner question:

How do I have my input code ignore certain strings of text?

What is your name human? I'm Fred

How old are you I'm Fred?

How do I ignore user input of the word "I'm"?

How old are you I'm Fred? I'm 25

Ahh, Fred, I'm 25 isn't that old.

How do I again ignore user input when dealing with integers instead?

This is the code I have so far:

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.")
          

CodePudding user response:

You could use .replace('replace what','replace with') in order to acheive that. In this scenario, you can use something like:

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.")

Similarly, you can use for the words you think the user might probably enter, this is one way of doing it.

CodePudding user response:

Why not use the list of words that should be ignored or removed from the input, i suggest you the following solution.

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.")

The output is following

enter image description here

  • Related