In Python, how to change text after it's printed?

后端 未结 5 745
名媛妹妹
名媛妹妹 2020-12-17 16:46

I have a Python program I am writing and I want it to be able to change text after it is printed. For example, let\'s say I want to print \"hello\" and erase one letter eve

5条回答
  •  半阙折子戏
    2020-12-17 17:31

    You could use this:

    call these modules:

    import time
    import sys
    

    Then copy this method:

        # Custom Print Method
        def custom_print(string, how = "normal", dur = 0, inline = True):
    

    Copy just this part for the method to do typing

    # string = the string to print & how = way to print & dur = time to print whole word or letter & inline = print on single line or not
    if how == "typing": # if how is equal to typing then run this block of code
        letter = 1
        while letter <= len(string):
            new_string = string[0:letter]
            if inline: sys.stdout.write("\r")
            sys.stdout.write("{0}".format(new_string))
            if inline == False: sys.stdout.write("\n")
            if inline: sys.stdout.flush()
            letter += 1 
            time.sleep(float(dur))
    

    OR just this part of the method for a string to print in reverse

    if how == "reverse": # if how is equal to reverse then run this block of code
        new_string = string
        while len(new_string) > 0:
            if inline == True: sys.stdout.write("\r")
            sys.stdout.write('{message: <{fill}}'.format(message=new_string, fill=str(len(string))))
            if inline == False: sys.stdout.write("\n")
            if inline == True: sys.stdout.flush()
            new_string = new_string[0:len(new_string) - 1]
            time.sleep(float(dur))
    

    OR just this part of the method for a normal string to print normally

    if how == "normal": # if how is equal to normal then run this block of code
        sys.stdout.write("\r")
        sys.stdout.write(string)
        time.sleep(float(dur))
        sys.stdout.write("\n")
    

    OR you can put all of it in the method for all the options

    All you have to do is call custom_print() instead ofprint`

    # custom_print("string", "howtoprint", seconds in int, inline:true or false)
    custom_print("hello", "reverse", 1) # for reverse printing hello
    custom_print("hello", "typing", 1) # for typing hello slowly
    custom_print("hello", "normal", 0) # for just printing hello
    custom_print("hello") # for just printing hello
    

提交回复
热议问题