That's what textwrap.wrap() does; it returns a list of lines, without newlines at the end. It's up to you to do whatever you need to with that.

As an aside, you should probably use a dict for the words and meanings, or an OrderedDict if you want to keep the order.

import textwrap

from collections import OrderedDict

words = ['a', 'the', 'go', 'python']
meanings = ['meaning1', 'meaning2', 'meaning3',
            'Python is a programming language that lets you work more quickly '
            'and integrate your systems more effectively. You can learn to '
            'use Python and see almost immediate gains in productivity and '
            'lower maintenance costs.']

wrapped_meanings = ['\n'.join(textwrap.wrap(meaning)) for meaning in meanings]

dictionary = OrderedDict(zip(words, wrapped_meanings))

for word, meaning in dictionary.items():
    print word
    print meaning
    print

Output:

a
meaning1

the
meaning2

go
meaning3

python
Python is a programming language that lets you work more quickly and
integrate your systems more effectively. You can learn to use Python
and see almost immediate gains in productivity and lower maintenance
costs.
Answer from Cyphase on Stack Overflow
🌐
PyPI
pypi.org › project › tabulate
tabulate · PyPI
Pretty-print tabular data in Python, a library and a command-line utility. ... printing small tables without hassle: just one function call, formatting is guided by the data itself · authoring tabular data for lightweight plain-text markup: multiple output formats suitable for further editing or transformation
      » pip install tabulate
    
Published   Mar 04, 2026
Version   0.10.0
🌐
DataCamp
datacamp.com › tutorial › python-tabulate
Python Tabulate: A Full Guide | DataCamp
September 5, 2024 - In the example below, the maxcolwidths is set to 30 characters to wrap the text data into multiple lines if it exceeds the specified number of characters. # Import tabulate library from tabulate import tabulate # Sample text data data = [ ["Alice", "Lorem ipsum dolor sit amet, consectetur adipiscing elit."], ["Bob", "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."], ["Charlie", "Ut enim ad minim veniam, quis nostrud exercitation ullamco."] ] # Creating a table with multiline cells table = tabulate( data, headers=["Name", "Description"], tablefmt="grid", maxcolwidths=[None, 30] # Set maximum width for the Description column ) print(table)
Top answer
1 of 3
2

That's what textwrap.wrap() does; it returns a list of lines, without newlines at the end. It's up to you to do whatever you need to with that.

As an aside, you should probably use a dict for the words and meanings, or an OrderedDict if you want to keep the order.

import textwrap

from collections import OrderedDict

words = ['a', 'the', 'go', 'python']
meanings = ['meaning1', 'meaning2', 'meaning3',
            'Python is a programming language that lets you work more quickly '
            'and integrate your systems more effectively. You can learn to '
            'use Python and see almost immediate gains in productivity and '
            'lower maintenance costs.']

wrapped_meanings = ['\n'.join(textwrap.wrap(meaning)) for meaning in meanings]

dictionary = OrderedDict(zip(words, wrapped_meanings))

for word, meaning in dictionary.items():
    print word
    print meaning
    print

Output:

a
meaning1

the
meaning2

go
meaning3

python
Python is a programming language that lets you work more quickly and
integrate your systems more effectively. You can learn to use Python
and see almost immediate gains in productivity and lower maintenance
costs.
2 of 3
1

use enumerate to go through the list, format to format your string output, join to merge the meanings.

word=['a','the','go','python']    
meaning= [['meaning1'], ['meaning2'], ['veryveryve', 'ryveryvery', 'veryveryve', 'ryveryvery', 'veryveryve', 'ryveryvery', 'veryverylo', 'ngmeaning3'], ['meaning4']]
for i, value in enumerate(word):
    print "{}\t{}".format(value, "\n\t".join(meaning[i]))

output

a   meaning1
the meaning2
go  veryveryve
    ryveryvery
    veryveryve
    ryveryvery
    veryveryve
    ryveryvery
    veryverylo
    ngmeaning3
python  meaning4
🌐
GitHub
github.com › thruston › python-tabulate
GitHub - thruston/python-tabulate: A neat-text-table filter · GitHub
If you do help, then tabulate will print "Try one of these:" followed by a list of all the defined verbs. Like this: Try one of these: add arr ditto dp dup filter gen group help label levels make noblanks nospace pivot pop push roll rule sf shuffle sort tap uniq unwrap unzip wrap xp zip
Author   thruston
🌐
GitHub
github.com › astanin › python-tabulate › blob › master › tabulate › __init__.py
python-tabulate/tabulate/__init__.py at master · astanin/python-tabulate
"""A custom implementation of CPython's textwrap.TextWrapper. This supports · both wide characters (Korea, Japanese, Chinese) - including mixed string. For the most part, the `_handle_long_word` and `_wrap_chunks` functions were · copy pasted out of the CPython baseline, and updated with our custom length · and line appending logic. """ · def __init__(self, *args, **kwargs): self._active_codes = [] self.max_lines = None # For python2 compatibility ·
Author   astanin
🌐
Lightrun
lightrun.com › answers › astanin-python-tabulate-wordwrap-with-long-lines-of-text-for-a-specific-column
Wordwrap with long lines of text for a specific column
And some more text.. Skipping this module...')] headers=("Module Name", "Result", "Comment") print(tabulate(results, headers, tablefmt="grid")) ... FYI, I had a need for this so have implemented most of this so far. Will plan on a PR in in the next few days. You’re welcome to look at it early if desired. https://github.com/astanin/python-tabulate/compare/master...magelisk:90-automatic-wordwrap?expand=1
🌐
Python
docs.python.org › 3 › library › textwrap.html
textwrap — Text wrapping and filling
Since the sentence detection algorithm relies on string.lowercase for the definition of “lowercase letter”, and a convention of using two spaces after a period to separate sentences on the same line, it is specific to English-language texts. ... (default: True) If true, then words longer than width will be broken in order to ensure that no lines are longer than width. If it is false, long words will not be broken, and some lines may be longer than width. (Long words will be put on a line by themselves, in order to minimize the amount by which width is exceeded.) ... (default: True) If true, wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English.
🌐
Bitbucket
bitbucket.org › astanin › python-tabulate › issues › 28 › feature-request-multiline-cells-and
astanin / python-tabulate / issues / #28 - Feature request: Multiline cells and headers — Bitbucket
April 14, 2014 - Default behaviour in previous versions was to always allow breaking hyphenated words.' data = [t.fill(text), 'yes', 1, 500] ``` ``` #!python >>>len(text) 385 >>>len(t.wrap(text)[0]) 78 ``` ``` #!python print(tabulate([data])) ``` Result: ``` ------------------------------------------------...
Find elsewhere
🌐
Arboreus
txt.arboreus.com › 2013 › 03 › 13 › pretty-print-tables-in-python.html
Pretty printing tables in Python
March 13, 2013 - Now tabulate formats data on a per-column basis; per-cell and per-row are also reasonable auto-formatting strategies. Deal with empty cells or occasional textual data in an otherwise numeric column (this may be useful to print tournament cross-tables, for example).
🌐
LinkedIn
linkedin.com › pulse › pretty-displaying-tricks-columnar-data-python-aadarsh-vadakattu
Pretty displaying tricks for columnar data in Python
May 23, 2019 - You can use a library called “tabulate” to easily display data in columns. It is as easy as wrapping a simple function to the print function used on the DataFrame.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › tabulate
Newest 'tabulate' Questions - Stack Overflow
How to set fixed column width in tabulate module of python eg: table_header = ['CURRENT TIME', 'NAMESPACE', 'CPU REQUESTS', 'CPU LIMITS', 'MEMORY REQUESTS', 'MEMORY LIMITS'] with open("abc.txt&...
🌐
Medium
medium.com › @HeCanThink › tabulate-your-go-to-solution-for-stylish-tables-in-python-35ede5145e28
Tabulate: Your Go-To Solution for Stylish Tables in Python 👉 | by Manoj Das | Medium
August 19, 2023 - The library supports various formatting styles, which can be customized to suit your preferences. Some common formatting styles include plain text, simple, grid, pipe, html, and latex. The Tabulate library was developed to address the need for easily creating formatted tables from various data sources in Python.
Top answer
1 of 2
5

You could use textwrap.wrap and tabulate:

#  pip install tabulate
from textwrap import wrap
from tabulate import tabulate

df_colnames_wrap = {k: '\n'.join(wrap(v, 20))
                    for k,v in df_colnames.items()}

print(tabulate(df.rename(columns=df_colnames_wrap),
               headers='keys', tablefmt='plain'))

Output:

      Lorem ipsum dolor        Consectetur    Fusce imperdiet      Vitae ultricies
               sit amet    adipiscing elit        libero arcu    augue molestie ac
 0                    0                  3                  1                  0.5
 1                    1                  5                  2                  1
 2                    2                  7                  3                  1.5
 3                    3                  9                  4                  2

With float formatting:

print(tabulate(df.rename(columns=df_colnames_wrap)
                 .convert_dtypes(),
               headers='keys', tablefmt='plain',
               floatfmt='.2f'
              ))

Output:

      Lorem ipsum dolor        Consectetur    Fusce imperdiet      Vitae ultricies
               sit amet    adipiscing elit        libero arcu    augue molestie ac
 0                    0                  3                  1                 0.50
 1                    1                  5                  2                 1.00
 2                    2                  7                  3                 1.50
 3                    3                  9                  4                 2.00
2 of 2
1

Pandas doesn't offer a built-in way to automatically wrap or break long column names across lines when you're turning a DataFrame into a string. The setting called max_colwidth only affects the data inside the table, not the column titles themselves. If you've tried adding your own line breaks in column names, you've noticed they don't actually change how the title is displayed; instead, you see "\n" characters in your output, which isn't what you want.

To get your column names to wrap onto multiple lines, you'll have to get a bit creative and do it yourself. You'll need to:

Write a function that can take a long column name and break it up into smaller parts, each part being short enough (for example, no more than 20 characters) to fit on its own line. Use this function to process all your column names, then adjust how your DataFrame is displayed so that these multi-line names look right. This method involves manually changing the column names to include line breaks where you want them and then making sure the DataFrame's string representation (when you print it out) respects these breaks. This is more about preparing your data and display settings before you actually print or show your DataFrame.

import pandas as pd

# Original DataFrame
df = pd.DataFrame({
    "LIDSA": [0, 1, 2, 3],
    "CAE": [3, 5, 7, 9],
    "FILA": [1, 2, 3, 4],
    "VUAMA": [0.5, 1.0, 1.5, 2.0],
})

# Dictionary with long column names
df_colnames = {
    "LIDSA": "Lorem ipsum dolor sit amet",
    "CAE": "Consectetur adipiscing elit",
    "FILA": "Fusce imperdiet libero arcu",
    "VUAMA": "Vitae ultricies augue molestie ac",
}

# Custom function to word-wrap text
def word_wrap(text, max_width):
    """
    Word-wrap text at a specified width. Attempts to break lines at word boundaries
    where possible.
    """
    words = text.split()
    lines = []
    current_line = []
    current_length = 0

    for word in words:
        if current_length + len(word) <= max_width:
            current_line.append(word)
            current_length += len(word) + 1  # +1 for space
        else:
            lines.append(' '.join(current_line))
            current_line = [word]
            current_length = len(word) + 1
    lines.append(' '.join(current_line))  # Add the last line

    return '\n'.join(lines)

# Apply word-wrap to column names
wrapped_colnames = {col: word_wrap(name, 20) for col, name in df_colnames.items()}

# Rename DataFrame columns
df = df.rename(columns=wrapped_colnames)

# Print the DataFrame with modified display settings
with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', 0, 'max_colwidth', 20, 'display.float_format', "{:.2f}".format):
    print(df.to_string())
🌐
GitHub
github.com › thruston › python-tabulate › blob › master › README.md
python-tabulate/README.md at master · thruston/python-tabulate
Tabulate is an exportable module that will line up tabular material automatically, and so save you hours of time faffing about with format and alignment. As a script it provides a filter with a simple DSL (domain-specific language) that can ...
Author   thruston
🌐
Medium
medium.com › @scriptopia › python-tabulate-print-tabular-data-in-python-976024451a58
Python tabulate — Print tabular data in Python - Scriptopia - Medium
December 17, 2022 - Here we create a script in Python that will print tabular data in Python using the ‘tabulate’ library which pretty-prints data to output.
🌐
Snyk
snyk.io › advisor › tabulate › functions › tabulate.preserve_whitespace
How to use the tabulate.PRESERVE_WHITESPACE function in tabulate | Snyk
June 22, 2022 - dbcli / cli_helpers / cli_helpers / tabular_output / tabulate_adapter.py View on Github · def adapter(data, headers, table_format=None, preserve_whitespace=False, **kwargs): """Wrap tabulate inside a function for TabularOutputFormatter.""" keys = ('floatfmt', 'numalign', 'stralign', 'showindex', 'disable_numparse') tkwargs = {'tablefmt': table_format} tkwargs.update(filter_dict_by_key(kwargs, keys)) if table_format in supported_markup_formats: tkwargs.update(numalign=None, stralign=None) tabulate.PRESERVE_WHITESPACE = preserve_whitespace return iter(tabulate.tabulate(data, headers, **tkwargs).split('\n'))
Top answer
1 of 1
1

See what you think about this. This post-processes textwrap.wrap to do justification:

import textwrap

def wrapme(s):

    width = 64
    lines = s.splitlines()
    result = []
    for l in lines:
        if len(l) < 64:
            result.append(l)
        else:
            breaks = textwrap.wrap( l, width, replace_whitespace=False, break_long_words=True, break_on_hyphens=False )
            for b in breaks[:-1]:
                if len(b) == 64:
                    result.append(b)
                    continue
                insert = 64-len(b)
                words = b.split()
                every = insert // (len(words)-1) + 1
                extra = insert % (len(words)-1)
                for i in range(extra):
                    words[i] += ' '
                result.append( (' '*every).join(words) )
            result.append( breaks[-1] )
    return result


for s in (
"Meta 335 to 95\n\nAmzn 188 to 96\n\nNflx 700 to 286\n\nSpot 305 to 80\n\nCRM 311 to 160\n\nSnap 57 to 10\n\nAmd 164 to 60\n\nARKK 126 to 39\n\nThese are all stocks off their Nov 2021 highs. Most of the market was poor phrasing, but this is some good perspective (instead of comparing vs the indices)"
,
"Meta 335 to 95\n\nAmzn 188 to 96\n\nNflx 700 to 286\n\nSpot 305 to 80\n\nCRM 311 to 160\n 57 to 10\n\nAmd 164 to 60\n\nARKK 126 to 39\n\nThese are all stocks off their Nov 2021 highs. Most of the market was poor phrasing, but this is some good perspective (instead of comparing vs the indices)"
,
"Meta 335Spot0  0nnR 1 o10n5 o1\\Ad14t 0nnRK16t rl tocks off their Nov 2021 highs. Most of the market was poor phrasing, but this is some good perspective (instead of comparing vs the indices)"
):
    for line in wrapme(s):
        print(f"|{line}|")

Output:

|Meta 335 to 95|
||
|Amzn 188 to 96|
||
|Nflx 700 to 286|
||
|Spot 305 to 80|
||
|CRM 311 to 160|
||
|Snap 57 to 10|
||
|Amd 164 to 60|
||
|ARKK 126 to 39|
||
|These  are  all  stocks  off  their  Nov 2021 highs. Most of the|
|market  was  poor  phrasing,  but  this is some good perspective|
|(instead of comparing vs the indices)|
|Meta 335 to 95|
||
|Amzn 188 to 96|
||
|Nflx 700 to 286|
||
|Spot 305 to 80|
||
|CRM 311 to 160|
| 57 to 10|
||
|Amd 164 to 60|
||
|ARKK 126 to 39|
||
|These  are  all  stocks  off  their  Nov 2021 highs. Most of the|
|market  was  poor  phrasing,  but  this is some good perspective|
|(instead of comparing vs the indices)|
|Meta 335Spot0  0nnR 1 o10n5 o1\Ad14t 0nnRK16t rl tocks off their|
|Nov  2021  highs. Most of the market was poor phrasing, but this|
|is some good perspective (instead of comparing vs the indices)|
🌐
Readthedocs
pyhdust.readthedocs.io › tabulate.html
tabulate: auxiliary module to tablature matrix — Python tools for the BeACoN group Stable documentation
>>> print(tabulate([["spam", 1, None], ... ["eggs", 42, 3.14], ... ["other", None, 2.7]], missingval="?")) ----- -- ---- spam 1 ? eggs 42 3.14 other ? 2.7 ----- -- ---- Various plain-text table formats (tablefmt) are supported: ‘plain’, ‘simple’, ‘grid’, ‘pipe’, ‘orgtbl’, ‘rst’, ‘mediawiki’,
🌐
Pythonrepo
pythonrepo.com › repo › astanin-python-tabulate-python-generating-and-working-with-logs
Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate. | PythonRepo
January 11, 2022 - In this case the command line utility will be installed to ~/.local/bin/tabulate on Linux and to %APPDATA%\Python\Scripts\tabulate.exe on Windows. To install just the library on Unix-like operating systems: ... The module provides just one function, tabulate, which takes a list of lists or another tabular data type as the first argument, and outputs a nicely formatted plain-text table: