Home > Back-end >  Check if a letter in a string if it is in which order?
Check if a letter in a string if it is in which order?

Time:02-01

Im working on a guess the word game and I need to check if a letter is in that string and if it is in which order?

And write some ugly code like that:

Create a list and chose random character in it

name_list = ["sound", "train", "table", "phone", "mouse", "water"]
pick_word = random.choice(name_list)

Dont allow more than one letter

        user_input = ''
        while True:
            user_input = input("Guess a letter: ")

            if len(user_input) == 1:
                break
            else:
                print("Please type only one letter")

And this for checking giving letter in that word and in which order

        if user_input in pick_word[0]:
            print("Correct")
            print(f"{user_input}____")
            user_input_two = input("Guess a letter: ")
            if user_input_two in pick_word[1]:
                print("Correct")
                print(f"{user_input}{user_input_two}___")
            if user_input_two in pick_word[2]:
                print("Correct")
                print(f"{user_input}_{user_input_two}__")
            if user_input_two in pick_word[3]:
                print("Correct")
                print(f"{user_input}__{user_input_two}_")
            if user_input_two in pick_word[4]:
                print("Correct")
                print(f"{user_input}___{user_input_two}")
        elif user_input in pick_word[1]:
            print(f"_{user_input}___")
        elif user_input in pick_word[2]:
            print(f"__{user_input}__")
        elif user_input in pick_word[3]:
            print(f"___{user_input}_")
        elif user_input in pick_word[4]:
            print(f"____{user_input}")
        else:
            print("Letter not in word")

its so much code so you can understand the deal with just this

        if user_input in pick_word[0]:
            print("Correct")
            print(f"{user_input}____")
            user_input_two = input("Guess a letter: ")
            if user_input_two in pick_word[1]:
                print("Correct")
                print(f"{user_input}{user_input_two}___")
            if user_input_two in pick_word[2]:
                print("Correct")
                print(f"{user_input}_{user_input_two}__")
            if user_input_two in pick_word[3]:
                print("Correct")
                print(f"{user_input}__{user_input_two}_")
            if user_input_two in pick_word[4]:
                print("Correct")
                print(f"{user_input}___{user_input_two}")

Its so much code that left and I will hate every second if I cant learn how to do it more professionally.

CodePudding user response:

Learning to write clean, readable code is a lifelong pursuit, and not something you should expect of yourself when you're first starting out. I'm definitely no expert, but I've studied computer science for 6 years now, and I still find new ways to clean up my code and make it more readable, and I can guess that that'll be the case moving forward.

That being said, this tutorial on iterating over strings may be helpful. Essentially, python strings are just arrays of characters, so you can loop through them, just like a list of numbers. Something like this may work:

for word in name_list:
   for letter in word:
      if user_input == letter:
         # Do thing when it is correct
      else:
         # Do thing when it is not correct

There's probably better ways out there to do it than that, but I'm sure this solution will suffice for what you're doing, or at least point you in the right direction. Good luck!

CodePudding user response:

I think you could use a separate list to track which letters have been guessed and render that to the user.

Here is one possible idea for tracking guesses: if the word were "train", initialize a list of all 5 underscore characters.

word = "train"
# initialize via ["_"] * len(word)
answer_tracker = ["_", "_", "_", "_", "_"]

When the user guesses a letter, you can check if the character is in the word using the str.index() method:

word.index("n") # returns 4

If you get a number back from str.index, you have a match. You could store that in your tracker array:

answer_tracker[4] = user_input # e.g. "n"

If the user input is not found in the word, then str.index will raise a ValueError.

try:
    index = word.index(user_input)
    answer_tracker[index] = user_input  # answer_tracker = ["_", "_", "_", "_", "n"]
except ValueError:
    pass  # tell user they didn't get a letter and return to input

You can render the guessed characters via:

print("".join(answer_tracker))  # outputs "____n" after first guess

The game would end once there are no underscore characters left in your tracker list.

  • Related