Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the visual length of a text string in python

Tags:

python

string

Similar to this question, I'm not asking how to find the number of characters in a string. I would like to determine the visual length of a string as rendered or compare it to another string.

For example, both 'iiii' and 'WWWW' have four characters. However, 'iiii' is shorter visually. I'm aware that this is determined by font, and I'm not working with monospaced fonts. So, for the purposes of this problem, I'll be using Arial 10pt.

Are there any built-in modules which will provide the visual dimensions of a string given a font?

like image 460
Fezter Avatar asked Sep 13 '15 22:09

Fezter


People also ask

How do I get the length of a string in Python?

Python len() function returns the length of the string.

What does Len () do in Python?

The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.

Can you use Len for strings in Python?

In programming languages, getting the length of a particular data type is a common practice. Python is no different because you can use the built-in len() function to get the length of a string, tuple, list, dictionary, or any other data type.


1 Answers

Instead of rendering into an image buffer and counting pixels, you can calculate width directly by using the font metrics. There doesn't seem to be a font API distributed with core python, but there are plenty of third-party ones in various packages. Here's a pretty complete solution for Adobe font metrics, using matplotlib:

>>> from matplotlib import rcParams
>>> import os.path

>>> afm_filename = os.path.join(rcParams['datapath'], 'fonts', 'afm', 'ptmr8a.afm')
>>>
>>> from matplotlib.afm import AFM
>>> afm = AFM(open(afm_filename, "rb"))
>>> afm.string_width_height('What the heck?')
(6220.0, 694)

The metrics are reported in units of 1/1000 of the scale factor (point size) of the font being used. (Thanks @JacobLee for digging up this information.)

Another possibility is the tkFont module of tkinter. This page documents the function tkFont.Font.measure("some string"), but it seems you need a Tk window before you can use it; so I don't know how practical it is:

# Python 3 names -- see Note below
import tkinter 
from tkinter import font as tkFont

tkinter.Frame().destroy()  # Enough to initialize resources
arial36b = tkFont.Font(family='Arial', size=36, weight='bold')
width = arial36b.measure("How wide is this?")
print(width)  # Prints: 404

Note: In python 2 (and in the page I mentioned above), tkinter is known as Tkinter, and tkinter.font is a top-level module, tkFont:

import Tkinter
import tkFont
like image 191
alexis Avatar answered Nov 01 '22 01:11

alexis