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
» pip install tabulate
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.
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
I can't comment. What does this "very long string" look like? I used this code below and it worked fine for me. My very long string was 2,970 characters long.
table = [["Sun"*990 ,696000,1989100000],["Earth",6371,5973.6],
["Moon",1737,73.5],["Mars",3390,641.85]]
print(tabulate(table))
Addressing comments. Yes, it is that way because there are no line returns in the string. I'm guessing the author of the package didn't want to arbitrarily add line returns. You can insert your own line returns and tabulate will handle them. The output is dependent on font size and screen width. If the length of the line surpasses your screen width then it wraps. I think that's what you mean by it looks bad. You can output to a file and view it (make sure to turn off any line wrap features).
Here is an example of how to do that.
from tabulate import tabulate
from pathlib import Path
table = [["Sun"*990,696000,1989100000],["Earth",6371,5973.6],
["Moon",1737,73.5],["Mars",3390,641.85]]
file_output = Path('test.txt')
file_output.write_text(tabulate(table))
Workaround: Pipe into a pager and disable wrapping, e.g. less -S or most
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
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())