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}")
Discussions

python 3.x - encode ,length of character and width of display in python3 - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
python 3.x - Width of character - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... New: Stack Overflow For Agents. The next generation of knowledge exchange. Learn more · pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learning... More on stackoverflow.com
🌐 stackoverflow.com
How to get Linux console window width in Python - Stack Overflow
I mean the number of characters ... pixel width of the window. ... Look this answer for a more extensive solution to have a "columns dependent" printing mechanism. stackoverflow.com/questions/44129613/… ... Please consider changing the accepted answer. The one you've selected is really janky, platform dependent, and it's using os.popen which is deprecated. The top-voted answer showing shutil is the best way. ... Not sure why it is in the module shutil, but it landed there in Python 3.... More on stackoverflow.com
🌐 stackoverflow.com
Width of a string with zero-width and two-width characters, in Python 3 in a terminal (not in a GUI) - Stack Overflow
I would like to format strings to show them with curses. For that, I would like to add spaces if the line is too short, and cut it and add continuation characters if it is too long. My problem is to More on stackoverflow.com
🌐 stackoverflow.com
🌐
Note.nkmk.me
note.nkmk.me › home › python
Get Image Size (Width, Height) with Python, OpenCV, Pillow (PIL) | note.nkmk.me
April 29, 2025 - h, w, c = im.shape print('width: ', w) print('height: ', h) print('channel:', c) # width: 400 # height: 225 # channel: 3 ... When unpacking a tuple, it is a common convention to assign unused values to _. In the following example, the number of colors (or channels) is not used:
🌐
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.
🌐
GitHub
github.com › jquast › wcwidth
GitHub - jquast/wcwidth: Python library that measures the width of strings in a terminal · GitHub
>>> from wcwidth import strip_sequences >>> strip_sequences('\x1b[31mred\x1b[0m') 'red' Some Unicode characters have "East Asian Ambiguous" (A) width. These characters display as 1 cell by default, matching Western terminal contexts, but many CJK (Chinese, Japanese, Korean) environments may have a preference for 2 cells. This is often found as boolean option, "Ambiguous width as wide" in Terminal Emulator software preferences.
Starred by 458 users
Forked by 66 users
Languages: Python 99.8% | Jinja 0.2%
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-get-linux-console-window-width-in-python
How to get Linux console window width in Python?
Another approach using the os.get_terminal_size() function (Python 3.3+): import os size = os.get_terminal_size() print(f"Columns: {size.columns}") print(f"Rows: {size.lines}") It can be easily seen that in both approaches using os.popen() or subprocess.check_output(), we are making use of Linux's utility command stty, which is used to print the terminal line settings or the characteristics of the Linux terminal. From this output, we extract the height and width values.
🌐
STEMpedia
ai.thestempedia.com › home › python functions › width()
width() - Object Detection Library - Python Function
July 24, 2022 - sprite = Sprite('Square Box') obj = ObjectDetection() obj.disablebox() obj.setthreshold(0.5) obj.analysestage() sprite.gotoxy(0, 0) sprite.setsize(100) sprite.say(str(obj.count()) + " Object Detected", 2) for object in range(1, obj.count() + 1): sprite.setx(obj.x(object)) sprite.sety(obj.y(object)) sprite.setsize(obj.width(object)) sprite.say(obj.classname(object) + " with " + str(obj.confidence(object)), 2) Detection at 0.3 ·
🌐
Programiz
programiz.com › python-programming › methods › string › ljust
Python String ljust()
Online Python Online JavaScript Online SQL Online Java Online HTML Online C Online C++ Online C# Online PHP Online Swift Online Kotlin Online TypeScript Online Go Online Rust Online Scala Online Dart Online R Online Ruby ... Here, fillchar is an optional parameter. ... width - width of the given string.
🌐
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.
🌐
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...
🌐
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.
🌐
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 ·
🌐
Python
wiki.python.org › moin › Py3kStringFormatting
String formatting methods in Python 3000, based on PEP ...
November 15, 2008 - This is used for printing fields in the form '+000000120'. This is only valid for numeric types. ... Forces the field to be centered within the available space. Note that unless a minimum field width is defined, the field width will always be the same size as the data to fill it, so that the ...
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().

🌐
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?
🌐
Stack Overflow
stackoverflow.com › questions › 20974943 › python3-strings-real-length-width
python 3.x - (Python3) string's (real) length/width - Stack Overflow
Nope. You're asking "get the width of this string", and I'm asking "in what units?", to which you can answer "in multiples of width of a dot". I can only answer that if you specify a font (see @tripleee's comment).
🌐
Reddit
reddit.com › r/pythontips › understanding width and precision in string formatting
r/pythontips on Reddit: Understanding width and precision in string Formatting
February 3, 2021 -

Hello friends,

Today I got stuck on a formatting issue and decided to learn more about the applications of width and precision with string Formatting of floats, integers and strings.

I have put down my learnings in an article and would like to share with you. Do share if there are other intricacies that I have missed!