python - 刽子手替换字符逻辑
问题描述
import random
import sys
words=["tumble","sigh","correction","scramble","building","couple","ton"]
computer=random.choice(words)
attm=7
chosen_word=len(computer)*"*"
print(chosen_word)
while attm>0:
print(computer)
print(chosen_word)
player_guess=str(input("guess: "))
if len(player_guess)>1:
player_guess=str(input("enter one character only: "))
if player_guess in computer:
print("you're right")
attm==attm
for i in chosen_word:
player_guess=chosen_word.replace(chosen_word,player_guess)
print(chosen_word)
else:
print("wrong!")
attm-=1
print("attempts= ",attm)
if attm==0:
print("you lost")
sys.exit
我希望每当玩家猜测它被替换为 selected_word 时,如果单词是“ton”,则正确的字符替换星号,如果玩家猜测是 (t),它将显示如下 *** 如果玩家猜测是 (t),则所选单词变为 (t* *) 等等简单的语法更可取,因为我是 python 新手
解决方案
您不能在 python 中更改字符串,它们是不可变的。而是使用列表。
将 更改chosen_word
为 a list
,list(string)
并在相应的索引处替换/更改它们。要打印,只需使用"".join(list)
创建一个新字符串即可很好地打印它。
此外,您遇到了一个错误,您将其与所选的 wors 进行了比较,这全部*
而不是实际的字母,因此除非您输入 ,否则您将永远找不到匹配项*
。
这里是完整的例子:
import random
import sys
words = ["tumble","sigh","correction","scramble","building","couple","ton"]
computer = random.choice(words)
attm = 7
chosen_word = ["*" for i in range(len(computer))]
while "*" in chosen_word and attm > 0:
print(computer)
print("".join(chosen_word))
player_guess = str(input("guess: "))[0] # take only the first character
if player_guess in computer:
print("you're right")
for idx, ch in enumerate(computer):
if player_guess == ch:
chosen_word[idx] = ch
print("".join(chosen_word))
else:
print("wrong!")
attm -= 1
print("attempts: ",attm)
if attm > 0:
print("You won!")
else:
print("You lost")
sys.exit
推荐阅读
- python - 用于实现分支定界技术以解决非凸非线性整数多目标优化问题的 Python 包?
- python - 如何区分不同服务器的 discord.py 余额?
- javascript - 如何按属性对数组对象进行分组?
- python - 用 30 秒的断点和颜色绘制时间序列数据
- r - 将变量分配给绘图标题中的 R 表达式
- java - SimpleDateFormat 中月份的奇怪问题
- c - 比较 char* 行中的第一个字符?
- javascript - 如何覆盖 Angular 库 scss 变量?
- r - 使用 bin 标签 ggplot 创建彩虹直方图
- docker - 使用 docker 运行 gitlab-ci 时缓存 maven 依赖项