Cannot pad python strings containing colorama

Viewed 22

I'm attempting to left pad a string in python3, but it doesn't seem to be working and I can't figure out why.

Below is an example of the code.

    import colorama
    def makeRed(text):
        return f'{colorama.Fore.RED}{text}{colorama.Style.RESET_ALL}'

    output = makeRed(str(4)).ljust(5)
    output += "example"
    print(output)

This outputs:

4example

with the 4 being in the colour red

It works fine without colorama, and I understand that there are alternatives to colorama, but any help with why this might be happening is much appreciated.

1 Answers

For those that stumble across this looking for an answer, check the length of the string!

While only one character is being printed, the length of the string was 9 (I suppose the colorama parameters count as characters in the output).

Therefore, to pad the string 4 spaces, I had to instead leftpad it 13.

Hope this helps those that were also looking for an answer to this!

Related