[Python] Python printing text: Highlight or mark some text in the string with indicators

Discussão em 'Python' iniciado por Stack, Junho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I want to print a string buffer (or byte array) which could contains some special characters, such as \t and \n, besides that, I need to print some indicators below the line to indicate some special part of the string, something like below:

    a b c d \t , e f g \n
    ~~~~~~~~ ^^^^^


    Here is the questions:

    1, the escape char and the normal char should be printed in a fixed width, but I see that repr() function can not.

    2, some indicator below the first line should be printed.

    3, if we still use repr() function, then I think the marker in the second line should be calculated dynamically, because repr() don't print texts in a fixed width format, thus a \t takes two chars.

    Any one can help?

    BTW: the whole idea is that I want to create a python pretty printer for GDB to show a token when debugging a parsing algorithm.

    EDIT: Here is an example:

    print (repr("abcd\t,efg\n"))


    when you run the code, you get a printed string which has 12 element instread of 10, for me, ff I want to hight the token "efg", which is the index 6,7,8 in the string, if I draw a markers in the second from the index 6,7,8, I get the following.

    abcd\t,efg\n
    ~~~


    Because the "\t" has two chars not the one, which means the function repr() don't print fixed witdh chars, in this case, I would like to see:

    abcd\t,efg\n
    ~~~

    Continue reading...

Compartilhe esta Página