How to get the length of a string without calculating the formatting of the text

Solution for How to get the length of a string without calculating the formatting of the text
is Given Below:

so for example I’m using a library called colored that can format strings for the console.
I’m trying to get the length of that string, but len() calculates the formatting letters too that don’t show up in the console… so for example, if I’m setting the string “test” to green it would look like this: “x1b[38;5;2mtest”,
when I print it it just prints test in green so I just want the letter count to show 4.
it doesn’t matter what library you are using the format would look the same. is there any way to get the length of a string and ignore it’s formatting?

Yes, there is. I made a function some time ago to do just this.

import re

def len_no_ansi(string):
    return len(re.sub(
        r'[u001Bu009B][[]()#;?]*((([a-zA-Zd]*(;[-a-zA-Zd/#&.:=?%@~_]*)*)?u0007)|((d{1,4}(?:;d{0,4})*)?[dA-PR-TZcf-ntqry=><~]))', '', string))

Credits: https://github.com/chalk/ansi-regex/blob/0755e661553387cfebcb62378181e9f55b2567ff/index.js

import re
s = "x1b[38;5;2mtest"
lenth = len(re.sub("\x1b[d*;d*;d*m", "", s))

Here is a explenation for the regex: https://regexr.com/630m7