Search code examples
pythonstring

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


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?


Solution

  • 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