Ilai K
Ilai K

Reputation: 111

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

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?

Upvotes: 3

Views: 1317

Answers (2)

user16442705
user16442705

Reputation:

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'[\u001B\u009B][\[\]()#;?]*((([a-zA-Z\d]*(;[-a-zA-Z\d\/#&.:=?%@~_]*)*)?\u0007)|((\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-ntqry=><~]))', '', string))

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

Upvotes: 4

awdr
awdr

Reputation: 72

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

Upvotes: 0

Related Questions