复制的代码功能不一样(刽子手)

时间:2016-12-03 13:19:53

标签: python python-3.x

我正在为学校项目制作一个刽子手剧本。我被卡住了,因为一行不能正常工作,即使副本在不同的脚本中工作(也包括在下面)。这是主要代码:

def random_word(word_list):
    global the_word
    the_word = random.choice(word_list)
    print (the_word)
    print (".")

def setup():
    global output_word
    size = 0   
    for c in the_word:
        size = size+1
    output_word = size*"_ "
    print (output_word, "("+str(size)+")")

def alter(output_word, guessed_letter, the_word):
    checkword = the_word
    print ("outputword:",output_word)
    previous = 0
    fully_checked = False
    while fully_checked == False:
        checkword = checkword[previous:]
        print ("..",checkword)
        if guessed_letter in checkword:
            the_index = (checkword.index(guessed_letter))
            print (output_word)
            print (the_index)
            print (guessed_letter)
  # Line below just won't work
            output_word= output_word.replace(output_word[the_index], guessed_letter)
            print (output_word)
            previous = the_index
            fully_checked = True

def guessing():
    global guessed_letter 
    guessed_letter = input("Enter a letter > ")    
    if guessed_letter in the_word:
        alter(output_word, guessed_letter, the_word)

所以行

output_word= output_word.replace(output_word[the_index], guessed_letter)

应打印类似_ _ _ _ g _ _ _(用于摆动的单词) 然而它打印

  

_g_g_g_g_g_g_g

这是完整输出:

costumed               #the_word
.
_ _ _ _ _ _ _ _  (8)   #output_word + size
Enter a letter > t
outputword: _ _ _ _ _ _ _ _ 
.. costumed #
_ _ _ _ _ _ _ _ 
3                      # the_index
t                      #guessed_letter
_t_t_t_t_t_t_t_t       #the new output_word

然而,在这个不同的测试代码中,一切正常:

output_word = "thisworkstoo"
the_index = output_word.find("w")
guessed_letter = "X"
output_word= output_word.replace(output_word[the_index], guessed_letter)
print (output_word)

输出:     thisXorkstoo

1 个答案:

答案 0 :(得分:0)

Replace用第二个参数替换它的所有第一个参数。所以说

 output_word= output_word.replace(output_word[the_index], guessed_letter)

当output_word = _ _ _ _ _ _ _ _将用guessed_letter替换每个下划线时。

所以我会这样:

output_word = list(output_word)
output_word[the_index] = guessed_letter
output_word = ''.join(i for i in output_word)

Shell示例:

>>> output_word = '_ _ _ _ _ _ _ _'
>>> the_index = 3
>>> guessed_letter = "t"
>>> output_word = list(output_word)
>>> output_word[the_index] = guessed_letter
>>> output_word = ''.join(i for i in output_word)
>>> output_word
'_ _t_ _ _ _ _ _'

更好的方法是:

output_word = output_word[:the_index] + guessed_letter + output_word[the_index+1]