擅长:python、mysql、java
<h2>.replace()并不像您认为的那样</h2>
<p><code>.replace</code>用第二个替换第一个<code>paramater</code>的所有出现。举个例子:</p>
<pre><code>"sentence".replace("e", "z")
</code></pre>
<p>将给出:</p>
<pre><code>"szntzncz"
</code></pre>
<p>在程序中要做的是在循环遍历每个<code>char</code>时,用<code>char</code>替换</strong>的<strong>索引,即并非所有字符都加下划线<code>_</code>。你知道吗</p>
<p>要替换字符串的索引,需要将其转换为带有<code>list()</code>的列表,然后更改所需的<code>index</code>,最后转换回带有<code>''.join()</code>的字符串。你知道吗</p>
<p>所以这条线:</p>
<pre><code>user_word = user_word.replace(user_word[word.index(char)], user_guess)
</code></pre>
<p>应改为:</p>
<pre><code>user_word = list(user_word)
user_word[word.index(char)] = user_guess
user_word = ''.join(user_word)
</code></pre>
<p>这会给你5个下划线中<code>z</code>的正确位置。你知道吗</p>
<p>可能还需要考虑将单词作为<code>chars</code>存储在一个列表中,因为这意味着您不必在每次猜测字母时都进行转换。如果您将它存储在一个列表中,您只需记住在为用户显示它时打印:<code>''.join(user_word)</code>。:)</p>