python如何以随机顺序缓慢显示字符串中的每个字母

问题描述 投票:0回答:2

是的,我知道替换方法不是我需要的,但我不知道该怎么做,它必须慢慢地显示单词中的字母,在代码下面我输入我想要的输出

import random
a = "hello"
x = "_" * len(a)
c = x.replace(x[random.randint(0, len(a) -1 )], a[random.randint(0, len(a) - 1)])
print(c)```


the output what i want is something like 

_____
2seconds later
__ll_
2sl...
h_ll_
2....
hell_
2...
hello

python logic
2个回答
3
投票

您可以通过多种方式做到这一点:通过替换、通过索引、通过正则表达式......

使用从白名单读取的正则表达式的简单实现:

from random import shuffle
from time import sleep
from re import sub

word, mask_char, whitelist = "hello", '_', ''
char_list = list(word)
sleep_time = 2

# Make the letters unique, then make it
# a list again, for later indexing:
char_list  = list(set(char_list))   

# Mix the order of the letters:
shuffle(char_list)    

# Print the full mask:
print(mask_char*len(word))
sleep(sleep_time)

# Print at each guess:
for ch in char_list:
    whitelist += ch
    print(sub(fr"[^{whitelist}]", mask_char, word))
    if ch != char_list[-1]:
        sleep(sleep_time)

2
投票

您需要时间模块来实现睡眠功能。然后,只需获取

a
字符串中的每个字母,对它们进行打乱,循环遍历它们,然后在每次迭代中循环
a
并替换 x 中的字母即可。

由于 python 中的字符串是不可变的,所以我制作了

x
一个列表。

from random import sample
from time import sleep

a = "hello"
x = ["_" for _ in a]
letters = frozenset(a)

for letter in sample(letters, len(letters)):
    print(''.join(x))
    for i, replace in enumerate(a):
        if replace == letter:
            x[i] = letter
    sleep(2)
print(''.join(x))
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.