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
🌐
ZetCode
zetcode.com › python › fstring
Python f-string - formatting strings in Python with f-string
May 11, 2025 - F-strings allow you to dynamically set the width and precision of your formatted output by using variables instead of hardcoded values. This provides great flexibility when you need to adjust formatting based on runtime conditions or user preferences. ... #!/usr/bin/python value = 123.456789 ...
Discussions

string - How do I format a number with a variable number of digits in Python? - Stack Overflow
With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to access previously defined variables with a briefer syntax: >>> name = "Fred" >>> f"He said his name is {name}." 'He said his name is Fred.' The examples given by John La Rooy can be written as · In [1]: num=123 ...: fill='0' ...: width... More on stackoverflow.com
🌐 stackoverflow.com
format - Python f-string with variable width alignment and variable text - Stack Overflow
I'm trying to randomize exam seating for different classrooms (in some classrooms one row can seat 4 students while in others one row can seat 3) and I drafted a Python script to print each student's More on stackoverflow.com
🌐 stackoverflow.com
python - Format string dynamically - Stack Overflow
We want to end up with s in our format string when the width is 20, so we use %%%ds and supply the width variable to substitute in there. The first two % signs become a literal %, and then %d is substituted with the variable. ... format_template = '%%%ds : %%%ds' # later: width = 20 formatter = format_template % (width, width) # even later: print formatter % ('Python... More on stackoverflow.com
🌐 stackoverflow.com
July 9, 2017
python - How to use variables for width and precision in str.format()? - Stack Overflow
How can I use a variable for the precision and width? ... A format_spec field can also include nested replacement fields within it. These nested replacement fields can contain only a field name; conversion flags and format specifications are not allowed. The replacement fields within the format_spec are substituted before the format_spec string ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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. ... With this syntax, you can even pass variables for each of those values for more dynamic control.
🌐
Peterbe.com
peterbe.com › plog › how-to-pad-fill-string-by-variable-python
How to pad/fill a string by a variable in Python using f-strings - Peterbe.com
January 24, 2020 - What also trips me up is, suppose that the number 10 is variable. I.e. it's not hardcoded into the f-string but a variable from somewhere else. Here's how you do it: >>> width = 10 >>> f'{mystr:<{width}}' 'peter ' >>> f'{mystr:>{width}}' ' peter'
🌐
Bentley
cissandbox.bentley.edu › sandbox › wp-content › uploads › 2022-02-10-Documentation-on-f-strings-Updated.pdf pdf
A Guide to Formatting with f-strings in Python - CIS Sandbox
shows how you can use f-strings to display the value of a variable in the form: variable ... What You Get (WYSIWYG). The procedure is as follows: • Placing between the quotation marks after the 'f' the text that you want displayed · • Enclosing the variables to be displayed within the text in curly braces · • Within those curly braces, placing a colon (:) after the variable · • Formatting the variable using a format specification (width, alignment, data type) after
🌐
GeeksforGeeks
geeksforgeeks.org › python › pad-or-fill-a-string-by-a-variable-in-python-using-f-string
Pad or fill a string by a variable in Python using f-string - GeeksforGeeks
July 15, 2025 - We can pad strings to the left, right, or centre by using f-strings with a variable as the padding character. ... f'{s:{pad_char}^{width}}' centers the string and pads both sides with the specified padding character (pad_char), ensuring the ...
Find elsewhere
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › hardware and peripherals › raspberry pi pico › micropython
f string for fixed width output - Raspberry Pi Forums
June 10, 2023 - The following works: temp = f'{number:.6f}' outputstring = f'{temp:.8}' The following doesn't work: outputstring = f'{ f'{number:.6f}':.8}' nor does the use of different quotes: outputstring = f'"{f'{number:.6f}':.8}" Am I missing something or is it not possible to do this with a single f string line? ... numbers = [ 1.234567, 12.34567, 123.4567, ] for n in numbers: print( f"9.5f: '{n:9.5f}'") 9 is total length, including the dot. 5 is the decimal places length. If number is too large and exceeds the total length, then python extends the length. Edit: does not solve OP problem to output numbers with full 8 char length needing variable precision.
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.org
discuss.python.org › python help
How to use f string format without changing content of string? - Python Help - Discussions on Python.org
June 15, 2022 - How to use f string format without changing content of string · It will lose a space character in second line. How can I prevent this behavior? I want to make a function to print the text above but the value in f string depend on the length of value current_money.
🌐
Built In
builtin.com › data-science › python-f-string
Guide to String Formatting in Python Using F-strings | Built In
More on Python: 5 Types of Arguments in Python Function Definitions · There are very few occasions when you’d need to align a word or text to the right or left, but this is the foundation to fully understanding how to add zeros to the left or right of a number. F-string is very useful when formatting numbers. Say we have a number, and we want to align it to the right. We can do that using the syntax above. In this case, we only need to add the width element.
🌐
Mimo
mimo.org › glossary › python › formatted-strings
Python Formatted Strings / f-string formatting Guide
f-strings can include more than variables and values. They can include expressions, function calls, and even conditional logic: ... Python's so-called format mini-language provides advanced control over string formatting. Instead of just inserting values, the format mini-language allows you to specify field width, alignment, precision, and more.
🌐
pythontutorials
pythontutorials.net › blog › format-string-in-python-with-variable-formatting
How to Dynamically Set Variable Widths in Python Format Strings: A Better Alternative to Clumsy Concatenation — pythontutorials.net
Python’s str.format() method and f-strings (introduced in Python 3.6) both support nested placeholders for dynamic widths. This lets you define the width using a variable, expression, or even another formatted value.
🌐
Medium
medium.com › bitgrit-data-science-publication › python-f-strings-tricks-you-should-know-7ce094a25d43
Python F-strings Tricks You Should Know | by Benedict Neo | bitgrit Data Science Publication | Medium
October 12, 2022 - With a str the method defined, you’d need to write !r to tell Python to print out the repr method instead. If you want your variables to be printed at a specific position, alignments are the way to go! Notice in the first line number:n . Here n stands for the width of space to print the variable number starting from the string “is” (inclusive of the variable itself)
🌐
OpenPython
openpython.org › home › articles › python f-strings guide: syntax, examples & format codes
Python f-strings Guide: Syntax, Examples & Format Codes | OpenPython
May 22, 2026 - Use conversion flags !s, !r, and !a to control representation; use = (since Python 3.8) to print expression and value for debugging. f-strings accept any valid Python expression, support datetime formatting with strftime codes, and let formatting parameters themselves be variables: f"{value:{width}.{precision}f}".