Using the f-string format becomes very easy nowadays.

If you were using

print(f'{token:10}')

And you want the 10 to be another variable (for example the max length of all the tokens), you would write

print(f'{token:{maxTokenLength}}')

In other words, enclose the variable within {}


In your particular case, all you need is this.

head = 'eggs', 'bacon', 'spam'  
w1, w2, w3 = 8, 7, 10  # column widths  

print(f'  {head[0]:>{w1}}  {head[1]:>{w2}}  {head[2]:>{w3}}')
print(f'  {"="*w1:>{w1}}  {"="*w2:>{w2}}  {"="*w3:>{w3}}')

Which produces

      eggs    bacon        spam
  ========  =======  ==========
Answer from Rub on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › format-a-number-width-in-python
Format a Number Width in Python - GeeksforGeeks
July 23, 2025 - This code demonstrates how to use f-strings in Python to format integers to fixed widths, with options to pad them with leading zeros or spaces, depending on the desired output format. ... my_num = 12 # formatting integer to a fixed width of 3 print(f"{my_num:03d}") # formatting integer to a fixed width of 4 print(f"{my_num:04d}") # formatting integer to a fixed width of 6 (with leading spaces) print(f"{my_num:6d}")
🌐
Note.nkmk.me
note.nkmk.me › home › python
Get Image Size (Width, Height) with Python, OpenCV, Pillow (PIL) | note.nkmk.me
April 29, 2025 - This article explains how to get the image size (width and height) in Python using OpenCV and Pillow (PIL). You can obtain the image size as a tuple using the shape attribute of ndarray in OpenCV and ...
🌐
DEV Community
dev.to › erictleung › print-fixed-fields-using-f-strings-in-python-26ng
Print fixed fields using f-strings in Python - DEV Community
August 20, 2020 - To do so, you can use the syntax used in other Python formatting. init = 34 end = 253 print(f"You had this much money : ${init:5}") print(f"Now you have this much money : ${end:5}") # You had this much money : $ 34 # Now you have this much money : $ 253 # Spacing width 12345 · Note the annotation of spacing width with the numbers 1 through 5 to show the spacing differences.
🌐
OpenStax
openstax.org › books › introduction-python-programming › pages › 8-4-string-formatting
8.4 String formatting - Introduction to Python Programming | OpenStax
March 13, 2024 - The width field refers to the minimum length of the string. The precision field refers to the floating-point precision of the given number. The type field shows the type of the input that is passed to the format() method.
🌐
LabEx
labex.io › tutorials › python-how-to-handle-string-width-in-python-419445
How to handle string width in Python | LabEx
In Python, string width refers to the visual space a string occupies when displayed, which is particularly important when dealing with text rendering, formatting, and internationalization.
🌐
DNMTechs
dnmtechs.com › adjusting-column-width-size-in-openpyxl-python-3-programming
Adjusting Column Width Size in openpyxl – Python 3 Programming – DNMTechs – Sharing and Storing Technology Knowledge
Adjusting column width in Excel files using openpyxl is a straightforward task in Python. By using the column_dimensions dictionary and the width property, we can easily modify the width of individual columns or multiple columns at once.
🌐
STEMpedia
ai.thestempedia.com › home › python functions › width()
width() - Object Detection Library - Python Function
July 24, 2022 - width() function is from Object Detection library of PictoBlox Python. This function returns the width of the object detected. You can specify the object for which the value is needed. The position is mapped with the stage coordinates.
Find elsewhere
🌐
Programiz
programiz.com › python-programming › methods › string › ljust
Python String ljust()
fillchar (Optional) - character to fill the remaining space of the width
🌐
Stack Overflow
stackoverflow.com › questions › 55067103 › width-of-character
python 3.x - Width of character - Stack Overflow
I have a problem with unicode characters, they are wider or narrower than an usual character. Code: for base in bases: print("'{}' ".format(base), end=''), time.sleep(1) print() for bit in...
🌐
Stack Overflow
stackoverflow.com › questions › 48598304 › width-of-a-string-with-zero-width-and-two-width-characters-in-python-3-in-a-ter
Width of a string with zero-width and two-width characters, in Python 3 in a terminal (not in a GUI) - Stack Overflow
def stringWidth(string): width = 0 for c in string: # For zero-width characters if unicodedata.category(c)[0] in ('M', 'C'): continue w = unicodedata.east_asian_width(c) if w in ('N', 'Na', 'H', 'A'): width += 1 else: width += 2 return width · Depending on your text, you may need to add other categores for zero-width characters. python · string · python-3.x ·
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-get-linux-console-window-width-in-python
How to get Linux console window width in Python?
In the case of the os module, we make use of the popen() method that is used to open a pipe to and from command which will help in retrieving the width and height of the Linux window. ... import os rowSize, columnSize = os.popen('stty size', 'r').read().split() print(rowSize) print(columnSize) Save the above shown code in a file with a .py extension and run the following command in the terminal. immukul@192 linux-questions-code % python code.py 38 130
🌐
Python
wiki.python.org › moin › Py3kStringFormatting
String formatting methods in Python 3000, based on PEP ...
November 15, 2008 - If the width field is preceded by a zero ('0') character, this enables zero-padding. This is equivalent to an alignment type of '=' and a fill character of '0'. The 'precision' is a decimal number indicating how many digits should be displayed after the decimal point in a floating point conversion.
🌐
DNMTechs
dnmtechs.com › printing-strings-at-a-fixed-width-in-python-3-no-colon-extension-required
Printing Strings at a Fixed Width in Python 3: No Colon Extension Required – DNMTechs – Sharing and Storing Technology Knowledge
The string format method in Python 3 provides a powerful way to format strings. It allows for the insertion of values into placeholders within a string, as well as the specification of various formatting options. One such option is the ability to specify a fixed width for a string.
Top answer
1 of 8
320

I find using str.format much more elegant:

>>> '{0: <5}'.format('s')
's    '
>>> '{0: <5}'.format('ss')
'ss   '
>>> '{0: <5}'.format('sss')
'sss  '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'

In case you want to align the string to the right use > instead of <:

>>> '{0: >5}'.format('ss')
'   ss'

Edit 1: As mentioned in the comments: the 0 in '{0: <5}' indicates the argument’s index passed to str.format().


Edit 2: In python3 one could use also f-strings:

sub_str='s'
for i in range(1,6):
    s = sub_str*i
    print(f'{s:>5}')
    
'    s'
'   ss'
'  sss'
' ssss'
'sssss'

or:

for i in range(1,5):
    s = sub_str*i
    print(f'{s:<5}')
's    '
'ss   '
'sss  '
'ssss '
'sssss'

of note, in some places above, ' ' (single quotation marks) were added to emphasize the width of the printed strings.

2 of 8
145

EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.

You can use string formatting like this:

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

Basically:

  • the % character informs python it will have to substitute something to a token
  • the s character informs python the token will be a string
  • the 5 (or whatever number you wish) informs python to pad the string with spaces up to 5 characters.

In your specific case a possible implementation could look like:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1

SIDE NOTE: Just wondered if you are aware of the existence of the itertools module. For example you could obtain a list of all your combinations in one line with:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

and you could get the number of occurrences by using combinations in conjunction with count().

🌐
GeeksforGeeks
geeksforgeeks.org › turtle-width-function-in-python
turtle.width() function in Python | GeeksforGeeks
July 20, 2020 - The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.window_width() This function is used to return the width of the turtle windo
🌐
Python Forum
python-forum.io › thread-18652.html
How can I get the width of a string in Python?
is there a way to get the width of a string in pixel or in inches using Python 3?