Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Suggestion] Text width (string length without sequences). #53

Open
rysson opened this issue Jan 11, 2024 · 2 comments
Open

[Suggestion] Text width (string length without sequences). #53

rysson opened this issue Jan 11, 2024 · 2 comments

Comments

@rysson
Copy link

rysson commented Jan 11, 2024

Yours lib is awesome, I used it for years.
Now I have a little problem, a have fine formatting and print table separated.

Is any way to find printable text width to calculate table cell width?
If not I suggest add a function to count length of the text without sequences.

Of course I can add some regex to transform text before taking its length but it'll be nice to have it out of the box.


EDIT: some example

rx_omit_sequences = re.compile(r'(?:\033\[|\x9b)[0-?]*[!-/]*[@-~]')

def text_width(s: str) -> int:
    return len(rx_omit_sequences.sub('', s))

s = f'{fg.red}This is red text!{fg.rs}'
print('-' * len(s))
print(s)
print('-' * text_width(s))

20240111-132352-231x50

@feluxe
Copy link
Owner

feluxe commented Jan 15, 2024

Thanks for your kind words! :-)

I'm not sure if I understand the use case yet. Couldn't you just write:

s = "This is red text!"

print('-' * len(s))
print(f'{fg.red}{s}{fg.rs}')
print('-' * len(s))

I usually apply the styling/formatting as the very last step. Adding styles and then remove them via regex doesn't seem right to me.

Maybe a util function would make sense, but I'm not sure if it's really needed. I could see it misused a lot.

@rysson
Copy link
Author

rysson commented Jan 17, 2024

Of course, I could 😃

I wrote a function to print data in table layout. I want to allow there use formatted strings too.

I could add separate table with formats (or use table with cell objects rather, text with align, formatting etc.).
Next replace format with callable, maybe some formats are complex.
It's going to be more complicated.

OK, I see, it's my problem, I've to think about it more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants