python - 删除打印语句中的字符

标签 python python-3.x

我正在尝试创建一个程序,它会输入需要输入的任何内容,有时它会犯一个错误并进行纠正,就像一个真实的人正在输入一样,这是我的代码:

import time
import sys
import random
import string 
import uuid

def my_random_string(string_length=4):
    random = str(uuid.uuid4())
    random = random.lower()
    random = random.replace("-","")
    return random[0:string_length]

def delay_print(s):
    for c in s:
        sys.stdout.write( '%s' % c )
        sys.stdout.flush()
        time.sleep(random.uniform(0.01,0.5))
        random_string = random.randint(0,6)
        if random_string == 5:
            sys.stdout.write(my_random_string(2))
            time.sleep(0.1)
            #delete the two characters

delay_print("Hello, and welcome to the Enrichment Centre")

我不知道如何删除我放置的两个字符。

最佳答案

退格字符\b将返回到前一个字符之前,但是随后需要将其键入以实际变为空白。最简单的方法是输入一个空格。然而,您在一个字符中的间距太远,因此您需要另一个退格键在空格之前。并且您希望循环发生两次以实际删除两个随机字符。这就是我所做的,使其看起来最令人信服地像是有人在打字:

    if random_string == 5:
        sys.stdout.write(my_random_string(2))
        sys.stdout.flush()
        time.sleep(0.1)
        for _ in range(2):
            sys.stdout.write('\b \b')
            sys.stdout.flush()
            time.sleep(0.1)

关于python - 删除打印语句中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34133706/

相关文章:

python - 使用列表位置中包含的项目进行计算(遗传算法适合度)

Python 而不是 True 或 False

Python - 查找 x-y 数据中 fork 的宽度

python - __getitem__ 或方括号用于递归数据结构

python - 为什么在 Python 中调用数字文字上的方法会出现语法错误?

python - 查找 Excel/CSV 文件的实际列引用 - Python Pandas

python - 手动提交偏移量到kafka主题的正确方法是什么

python - 织物与预期

Python:如何启动完整进程而不是子进程并检索 PID

python - 寻找最大的质因数(最快的程序)