0

EDIT - The problem that I was having was with the library that i was trying to use, colorama, I probably should have been more specific.

I want to be able to print a string character-by-character with an extrememly short pause inbetween each character for effect but my code ignores control characters and just prints the individual characters. Not sure how to counter this.

Here is the part of the code that does it:

import time, sys    

def slowprint(message, speed):    
    for x in range(0, len(message)):    
        if x == len(message)-1:
            print(message[x])
        else:
            print(message[x], end="")
            sys.stdout.flush()
            time.sleep(speed)

I'm on python 3.2.

Shimshar
  • 3
  • 9

2 Answers2

0

Maybe something like this ?

import time, sys

def slowprint(message, speed):
    i = iter(message)
    # output first character before pausing
    sys.stdout.write(next(i))
    sys.stdout.flush()

    for letter in i:
        time.sleep(speed)
        sys.stdout.write(letter)
        sys.stdout.flush()

EDIT: fixed

Work of Artiz
  • 1,085
  • 7
  • 16
0

I'm not completely sure to understand your question, but I'll assume you're trying to print control characters like '\t' or '\n'.

When you create a string like "A\tB" it's made of three characters and not four. '\t' get converted to a single character directly.

So when you iterate through characters you'd need to map back these control characters to their string representation. For this you can use repr() (see this answer) and you're good

>>> slowprint(repr("abs\tsd\n"), 0.1)
Community
  • 1
  • 1
Benoit Seguin
  • 1,937
  • 15
  • 21
  • This would print the backslash separately from the next character (after time delay -- but that may be acceptable. The alternative is to do the `repr(c)[1:-1]` inside the loop. The slice removes the quotes around. But it is strange, anyway. ;) – pepr Jan 20 '16 at 19:26