简体   繁体   English

如何从字符串中获取重复字符的索引?

[英]How can I get the index of a recurring character from a string?

I'm working with a hangman like project whereas if the user inputs a letter and matches with the solution, it replaces a specific asterisk that corresponds to the position of the letter in the solution. 我正在使用类似子手的项目,但是如果用户输入字母并与解决方案匹配,它将替换对应于解决方案中字母位置的特定星号。 I'm trying to do this by getting the index of the instance of that letter in the solution then replacing the the matching index in the asterisk. 我正在尝试通过在解决方案中获取该字母实例的索引,然后替换星号中的匹配索引来做到这一点。

The thing here is that I only get the first instance of a recurring character when I used var.index(character) whereas I also have to replace the other instance of that letter. 这里的问题是,当我使用var.index(character)时,我仅获得重复字符的第一个实例,而我还必须替换该字母的另一个实例。 Here's the code: 这是代码:

word = 'turtlet'
astk = '******'

for i in word:
    if i == t:
        astk[word.index('i')] = i

Here it just replaces the first instance of 't' every time. 在这里,它每次都仅替换“ t”的第一个实例。 How can I possibly solve this? 我该如何解决?

index() gives you only the index of the first occurrence of the character (technically, substring) in a string. index()仅给您字符串中字符首次出现的索引(从技术上讲,是子字符串)。 You should take advantage of using enumerate() . 您应该利用使用enumerate()优势。 Also, instead of a string, your guess (hidden word) should be a list, since strings are immutable and do not support item assignment, which means you cannot reveal the character if the user's guess was correct. 另外,您的猜测(隐藏的单词)应该是列表,而不是字符串,因为字符串是不可变的,并且不支持项目分配,这意味着如果用户的猜测正确,则您无法显示字符。 You can then join() it when you want to display it. 然后,您可以在想要显示它时join()它。 Here is a very simplified version of the game so you can see it in action: 这是游戏的非常简化的版本,因此您可以在游戏中看到它:

word = 'turtlet'
guess = ['*'] * len(word)

while '*' in guess:

    print(''.join(guess))

    char = input('Enter char: ')

    for i, x in enumerate(word):
        if x == char:
            guess[i] = char

print(''.join(guess))
print('Finished!')

Note the the find method of the string type has an optional parameter that tells where to start the search. 请注意,字符串类型的find方法具有一个可选参数,该参数指示从何处开始搜索。 So if you are sure that the string word has at least two t s, you can use 因此,如果您确定字符串word至少有两个t s,则可以使用

firstindex = word.find('t')
secondindex = word.find('t', firstindex + 1)

I'm sure you can see how to adapt that to other uses. 我相信您可以看到如何将其调整为其他用途。

I believe there's a better way to do your specific task. 我相信有更好的方法来完成您的特定任务。

Simply keep the word (or phrase) itself and, when you need to display the masked phrase, calculate it at that point. 只需保留单词(或短语)本身,然后在需要显示被屏蔽的短语时,在该位置进行计算即可。 The following snippet shows how you can do this: 以下代码段显示了如何执行此操作:

>>> import re
>>> phrase = 'My hovercraft is full of eels'
>>> letters = ' mefl'
>>> display = re.sub("[^"+letters+"]", '*', phrase, flags=re.IGNORECASE)
>>> display
'M* ***e****f* ** f*ll *f eel*'

Note that letters should start with the characters you want displayed regardless (space in my case but may include punctuation as well). 请注意, letters应该以您要显示的字符开头(无论如何,在我的情况下为空格,但也可以包含标点符号)。 As each letter is guessed, add it to letters and recalculate/redisplay the masked phrase. 在猜测每个字母时,将其添加到letters然后重新计算/重新显示被屏蔽的短语。

The regular expression substitution replaces all characters that are not in letters , with an asterisk. 正则表达式替换替换并非适用于所有的字符letters ,有星号。

for i in range(len(word)):
    if word[i] == "t":
        astk = astk[:i] + word[i] + astk[i + 1:]

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

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