slice/stride by variable?

background

I'm attempting to code a basic letter game in python. In the game, the computer moderator picks a word out of a list of possible words. Each player (computer AI and human) is shown a series of blanks, one for each letter of the word. Each player then guesses a letter and a position, and are told one of the following:

  • That letter belongs in that position (the best outcome)
  • That letter is in the word, but not in that position
  • That letter is not in any of the remaining blank spaces
  • When the word has been fully revealed, the player to guess the most letters correctly wins a point. The computer moderator picks another word and starts again. The first player to five points wins the game. In the basic game, both players share the same set of blanks they're filling in, so the players benefit from each other's work.

    my question

    Is there any way to use a variable containing an integer to designate the degree of a slice/stride?

    because the secret word is randomized, I have no way of knowing how many characters it will contain. I want to check the user's input (guess) first based on its accuracy in regards to the place value the user selected, before checking to see if the letter appears in the secret word at all (not just exclusively in the place they specified). I'm thinking that I could maybe use len() to determine the number of places in the secret word, then use the player's numerical input to slice/stride over to the correct character place in the word specified by the player.

    How do I get the user-supplied integer into the slice/stride command? It doesn't seem to accept assigning input to a variable and then placing the variable within the slice/stride.

    I'm a beginner with python so apologies if this is a dumb question--my initial research didn't turn up anything.


    Simply put, yes, you can do this. You'd want to ensure that the input you're getting actually is an int , and work with it from there.

    some_word = "This is the song that doesn't end"
    stride = int(raw_input("Stride distance? "))
    
    print some_word[::stride]  # prints out "Ti stesn htdented"
    

    After looking in comments, you can isolate a single character in a string/sequence by indexing into it.

    some_word = "This is the song that doesn't end"
    iso = int(raw_input("Isolated character? "))
    
    print some_word[iso] # prints out whatever character is in that position, 0-based.
    

    看起来像这样做了,试图根据2的用户输入隔离“伙计”中的“u”。

    userGuessPosition = 2
    
    secretWord = ('dude')
    slice1 = (secretWord.__len__()) - userGuessPosition - 1
    print (secretWord[slice1:userGuessPosition])
    
    链接地址: http://www.djcxy.com/p/26756.html

    上一篇: Python列表使用切片扩展功能

    下一篇: 切片/跨度由变量?