You can do this using the str.format() method.

>>> width = 20
>>> print("{:>{width}} : {:>{width}}".format("Python", "Very Good", width=width))
              Python :            Very Good

Starting from Python 3.6 you can use f-string to do this:

In [579]: lang = 'Python'

In [580]: adj = 'Very Good'

In [581]: width = 20

In [582]: f'{lang:>{width}}: {adj:>{width}}'
Out[582]: '              Python:            Very Good'
Answer from Sede on Stack Overflow
🌐
DZone
dzone.com › data engineering › data › python string format examples
Python String Format Examples
January 23, 2020 - That brings us to Python's native string format() method. Introduced in Python 3, this method provides a simple way to construct and format strings with dynamic substitutions.
People also ask

How can I format strings with variable widths in Python?
A: You can use the str.format() method, f-strings, or padding techniques with the % operator to dynamically adjust the width of formatted strings.
🌐
sqlpey.com
sqlpey.com › python › top-4-ways-to-dynamically-format-strings-in-python
Top 4 Ways to Dynamically Format Strings in Python - sqlpey
What is the advantage of using f-strings over other methods?
A: F-strings offer improved readability and performance, allowing you to embed expressions directly within string literals, simplifying the syntax.
🌐
sqlpey.com
sqlpey.com › python › top-4-ways-to-dynamically-format-strings-in-python
Top 4 Ways to Dynamically Format Strings in Python - sqlpey
Can I use these techniques with list items?
A: Yes, you can apply any of these string formatting methods with items from lists or tuples, just as demonstrated with the zip method above.
🌐
sqlpey.com
sqlpey.com › python › top-4-ways-to-dynamically-format-strings-in-python
Top 4 Ways to Dynamically Format Strings in Python - sqlpey
🌐
GeeksforGeeks
geeksforgeeks.org › python › string-formatting-in-python
String Formatting in Python - GeeksforGeeks
String formatting in Python is used to insert variables and expressions into strings in a readable and structured way. It helps create dynamic output and improves the clarity and presentation of text in programs.
Published: March 18, 2026
🌐
Real Python
realpython.com › python-string-formatting
Python String Formatting: Available Tools and Their Features – Real Python
December 1, 2024 - Python’s string formatting mini-language offers several features, including string alignment, type conversion, numeric formatting, and dynamic formatting.
🌐
Real Python
realpython.com › python-formatted-output
A Guide to Modern Python String Formatting Tools – Real Python
February 1, 2025 - In modern Python, you have f-strings and the .format() method to approach the tasks of interpolating and formatting strings. These tools help you embed variables and expressions directly into strings, control text alignment, and use custom format ...
🌐
Python
docs.python.org › 3 › library › string.html
string — Common string operations
These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.
🌐
GeeksforGeeks
geeksforgeeks.org › string-formatting-in-python-using
Python Modulo String Formatting - GeeksforGeeks
March 12, 2024 - In Python, the %s format specifier is used to represent a placeholder for a string in a string formatting operation. It allows us to insert values dynamically into a string, making our code more flexible and readable.
Find elsewhere
🌐
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
Additionally, new style formatting allows all of the components of the format to be specified dynamically using parametrization.
🌐
sqlpey
sqlpey.com › python › top-4-ways-to-dynamically-format-strings-in-python
Top 4 Ways to Dynamically Format Strings in Python - sqlpey
December 6, 2024 - A: You can use the str.format() method, f-strings, or padding techniques with the % operator to dynamically adjust the width of formatted strings.
Top answer
1 of 4
2

Using no packages and no modules:

nums= [[  3, 4, -4,  -8, -10, -12,], [  5, 5,  3,  -3,  -4, -44,], [ 34,-4,-34, -22,  22,  22]]

t = ['|' + ''.join('%4i' % i for i in row) + ' |' for row in nums]
hdr = '+' +  (len(t[0])-2) * '-' + '+'
print '\n'.join( [hdr] + t + [hdr] )

This produces the output:

+-------------------------+
|   3   4  -4  -8 -10 -12 |
|   5   5   3  -3  -4 -44 |
|  34  -4 -34 -22  22  22 |
+-------------------------+

How it works:

  • t = ['|' + ''.join('%4i' % i for i in row) + ' |' for row in nums]

    t contains everything except the top and bottom rows. At its heart, the numbers are formatted as fixed width and aligned according to specification %4i. %4i means allow four spaces, format as an integer, and align right. Many other specifications are possible. If you wanted, for example, to 5-space wide integers aligned left, use %-5i.

  • hdr = '+' + (len(t[0])-2) * '-' + '+'

    Now that the interior rows are saved in t, we can assemble the header and trailer lines. These lines begin and end with a plus sign. The rest are filled with -.

  • print '\n'.join( [hdr] + t + [hdr] )

    This adds the hdr string to the beginning and end of the list of rows t and then joins all the rows together with newline characters to make the final table.

More complex example

Let's format the above table but add the min, max, mean, and standard deviation for each row at the end of each row.

def mmmsd(row):
    mean=sum(row)/len(row)
    stddev = ( sum( (x-mean)**2.0 for x in row ) / float(len(row)) )**0.5
    return '%6i%6i%6.2f%6.2f' % (min(row), max(row), mean, stddev)

nums= [[  3, 4, -4,  -8, -10, -12,], [  5, 5,  3,  -3,  -4, -44,], [ 34,-4,-34, -22,  22,  22]]

stats = [mmmsd(row) for row in nums]
t = [10*' ' + '|' + ''.join('%6i' % i for i in row) + ' |' + st for row, st in zip(nums, stats)]
hdr = 10*' ' + '+' +  (len(t[0])-12 - len(stats[0])) * '-' + '+' + len(stats[0]) * ' '
print '\n'.join( [hdr] + t + [hdr] )

This produces the result:

          +-------------------------------------+
          |     3     4    -4    -8   -10   -12 |   -12     4 -5.00  6.18
          |     5     5     3    -3    -4   -44 |   -44     5 -7.00 17.23
          |    34    -4   -34   -22    22    22 |   -34    34  3.00 24.92
          +-------------------------------------+                        
2 of 4
2

This is what I like about Python - there is always something stopping you from reinventing the wheel.

For your use case, prettytable is a good fit:

import prettytable

l = [
    [3, 4, -4, -8, -10, -12],
    [5, 5, 3, -3, -4, -44],
    [34, -4, -34, -22, 22, 22]
]

table = prettytable.PrettyTable(header=False, vrules=prettytable.FRAME)
for row in l:
    table.add_row(row)

print table

Prints:

+----+----+-----+-----+-----+-----+
| 3  | 4  |  -4 |  -8 | -10 | -12 |
| 5  | 5  |  3  |  -3 |  -4 | -44 |
| 34 | -4 | -34 | -22 |  22 |  22 |
+----+----+-----+-----+-----+-----+

Also check Manually changing table style paragraph of the package documentation page.


There is also texttable, but it is less powerful in terms of tweaking the table look&feel:

import texttable

l = [
    [3, 4, -4, -8, -10, -12],
    [5, 5, 3, -3, -4, -44],
    [34, -4, -34, -22, 22, 22]
]

table = texttable.Texttable()
table.add_rows(l, header=False)

print table.draw()

Prints:

+----+----+-----+-----+-----+-----+
| 3  | 4  | -4  | -8  | -10 | -12 |
+----+----+-----+-----+-----+-----+
| 5  | 5  | 3   | -3  | -4  | -44 |
+----+----+-----+-----+-----+-----+
| 34 | -4 | -34 | -22 | 22  | 22  |
+----+----+-----+-----+-----+-----+

Another option is tabulate which introduces a set of pre-defined table formats, e.g. "grid":

from tabulate import tabulate

l = [
    [3, 4, -4, -8, -10, -12],
    [5, 5, 3, -3, -4, -44],
    [34, -4, -34, -22, 22, 22]
]

table = tabulate(l, tablefmt="grid")
print table

Prints:

+----+----+-----+-----+-----+-----+
|  3 |  4 |  -4 |  -8 | -10 | -12 |
+----+----+-----+-----+-----+-----+
|  5 |  5 |   3 |  -3 |  -4 | -44 |
+----+----+-----+-----+-----+-----+
| 34 | -4 | -34 | -22 |  22 |  22 |
+----+----+-----+-----+-----+-----+

Also see relevant threads:

  • Formatting text in tabular form with Python
  • A Text Table Writer/Printer for Python
🌐
Developmentality
developmentality.wordpress.com › 2012 › 05 › 17 › hello-planet_name-creating-dynamicstrings-in-python
Hello {planet_name}: Creating strings with dynamic content in Python | Developmentality
May 17, 2012 - would produce “hello world”. Python has this feature built in to strings with the % operator. You can read more in depth about the [String Formatting Operations][] and its syntax, but at the very least you should memorize the flags %d (for integer types), %f (for floating point), and %s (for strings).
🌐
Python Forum
python-forum.io › thread-24481.html
dynamic f-string example
you might want to put this script in your python examples folder. you won't likely ever need to do this, but if some day you need to dynamically change the format of an f-string at run time (normally, python constructs code from an f-string at compi...
🌐
GeeksforGeeks
geeksforgeeks.org › string-formatting-in-python
Python String Formatting - How to format String? - GeeksforGeeks
format() method in Python is a tool used to create formatted strings. By embedding variables or values into placeholders within a template string, we can construct dynamic, well-organized output.
Published: August 21, 2024
🌐
Real Python
realpython.com › python-f-strings
Python's F-String for String Interpolation and Formatting – Real Python
November 30, 2024 - Pythonista! You can support multiple languages using string templates. Then, you can handle localized string formatting based on the user’s locale. The .format() method will allow you to dynamically interpolate the appropriate strings depending on the user’s language selection.
🌐
Vocal Media
vocal.media › education › mastering-python-f-strings-unleashing-the-power-and-tricks-of-dynamic-string-formatting
Mastering Python F-Strings: Unleashing the Power and Tricks of Dynamic String Formatting | Education
For example, Python's f-strings offer powerful formatting specifiers that allow precise control over the appearance of values, such as specifying width, precision, and alignment. JavaScript's string interpolation, on the other hand, primarily focuses on variable substitution and dynamic content insertion.
🌐
Programiz
programiz.com › python-programming › methods › string › format
Python String format()
There's an easier way to format dictionaries in Python using str.format(**mapping). # define Person dictionary person = {'age': 23, 'name': 'Adam'} # format age print("{name}'s age is: {age}".format(**person)) ** is a format parameter (minimum field width). You can also pass format codes like precision, alignment, fill character as positional or keyword arguments dynamically. # dynamic string format template string = "{:{fill}{align}{width}}" # passing format codes as arguments print(string.format('cat', fill='*', align='^', width=5)) # dynamic float format template num = "{:{align}{width}.{precision}f}" # passing format codes as arguments print(num.format(123.236, align='<', width=8, precision=2)) Output ·
🌐
Python
peps.python.org › pep-3101
PEP 3101 – Advanced String Formatting | peps.python.org
This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing ‘%’ string formatting operator.