gpt4 book ai didi

python - 如何使用迭代和变量替换字符串中的字符? (Python)

转载 作者:太空宇宙 更新时间:2023-11-04 03:50:19 25 4
gpt4 key购买 nike

作为大学项目的一部分,我正在用 Python 编写刽子手游戏,我正在尝试使用 string.replace(old, new) 将空格 (_) 替换为字母。不过,我没有使用实际的字符串字符,而是尝试对“旧”和"new"使用变量。到目前为止,这是我得到的:

if validGuess == 'true':
if guess in word:
for letter in word:
if letter == guess:
word.replace(letter, guess)
else:
missNum = (missNum + 1)
else:
tryNum = (tryNum - 1)

但是,它不起作用。我没有收到任何错误,它根本不会替换空白。

我在这里做错了什么?有没有更好的方法来实现我正在做的事情?

-编辑-

我尝试实现@Peter WeSTLake 的解决方案(在我看来这是最优雅的)但我遇到了一个问题。我有一段代码将随机选择的单词转换为下划线:

#converting word to underscores
wordLength = len(word)
wordLength = (wordLength - 1)
print(wordLength) #testing
for i in range(0,wordLength):
wordGuess = (wordGuess + '_')
print(wordGuess)

这似乎工作正常。这是字母替换的代码:

if validGuess == 'true':
wordGuess = ''.join([letter if guess == letter else wordGuess[pos]
for pos, letter in enumerate(word)])

if guess not in word:
tryNum = (tryNum - 1)

print(wordGuess)

但是,这里是输出:

Guess a letter: a
test
Traceback (most recent call last):
File "G:\Python\Hangman\hangman.py", line 60, in <module>
for pos, letter in enumerate(word)])
File "G:\Python\Hangman\hangman.py", line 60, in <listcomp>
for pos, letter in enumerate(word)])
IndexError: string index out of range

字符串索引超出范围?这是什么意思?

最佳答案

str.replace() 返回新字符串,存储新值:

word = word.replace(letter, guess)

Python 字符串是不可变的,不能就地改变。

但是,您正在用完全相同的值替换 letterletter == guess 仅当两个字符相同时才为真。

我会保留一组单独的正确猜测的字母,并每次都重建显示的下划线和正确的猜测:

correct_guesses = set()
incorrect_guesses = set()

if guess in correct_guesses & incorrect_guesses:
print('You already guessed that letter')

elif guess in word:
# correct guess!
correct_guesses.add(guess)
display_word = ''.join(char if char in correct_guesses else '_' for char in word)

else:
# incorrect guess!
incorrect_guesses.add(guess)
print('Oops, incorrect guess!')
missNum += 1

关于python - 如何使用迭代和变量替换字符串中的字符? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21578471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com