You could use textwrap module:

>>> import textwrap
>>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
>>> print(textwrap.fill(strs, 20))
In my project, I
have a bunch of
strings that are
read in from a file.
Most of them, when
printed in the
command console,
exceed 80 characters
in length and wrap
around, looking
ugly.

help on textwrap.fill:

>>> textwrap.fill?

Definition: textwrap.fill(text, width=70, **kwargs)
Docstring:
Fill a single paragraph of text, returning a new string.

Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph.  As with wrap(), tabs are expanded and other
whitespace characters converted to space.  See TextWrapper class for
available keyword args to customize wrapping behaviour.

Use regex if you don't want to merge a line into another line:

import re


strs = """In my project, I have a bunch of strings that are.
Read in from a file.
Most of them, when printed in the command console, exceed 80.
Characters in length and wrap around, looking ugly."""

print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs)))

# Reading a single line at once:
for x in strs.splitlines():
    print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))

output:

In my project, I have a bunch of strings
that are.
Read in from a file.
Most of them, when printed in the
command console, exceed 80.
Characters in length and wrap around,
looking ugly.
Answer from Ashwini Chaudhary on Stack Overflow
🌐
Python
docs.python.org › ja › 3 › library › textwrap.html
textwrap --- テキストの折り返しと詰め込み — Python 3.14.3 ドキュメント
1段落の文字列 text を、各行が width 文字以下になるように wrap します。 wrap のすべてのオプションは TextWrapper インスタンスの属性から取得します。結果の、行末に改行のない行のリ...
🌐
Python
docs.python.org › 3 › library › textwrap.html
textwrap — Text wrapping and filling
All wrapping options are taken from instance attributes of the TextWrapper instance. Returns a list of output lines, without final newlines. If the wrapped output has no content, the returned list is empty. ... Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. ... © Copyright 2001 Python Software Foundation.
🌐
Python
bugs.python.org › issue1859
Issue 1859: textwrap doesn't linebreak on "\n" - Python tracker
January 17, 2008 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/46167
🌐
W3Schools
w3schools.com › python › ref_module_textwrap.asp
Python textwrap Module
The textwrap module provides functions for wrapping and formatting plain text.
🌐
GeeksforGeeks
geeksforgeeks.org › python › textwrap-text-wrapping-filling-python
Textwrap – Text wrapping and filling in Python - GeeksforGeeks
May 31, 2017 - textwrap.wrap(text, width=70, **kwargs): This function wraps the input paragraph such that each line in the paragraph is at most width characters long. The wrap method returns a list of output lines.
🌐
Martin Heinz
martinheinz.dev › blog › 108
Everything You Can Do with Python's textwrap Module | Martin Heinz | Personal Website & Blog
February 7, 2024 - # Ugly formatting: multiline_string = """ First line Second line Third line """ from textwrap import dedent multiline_string = """ First line Second line Third line """ print(dedent(multiline_string)) # First line # Second line # Third line # Notice the leading blank line... # You can use: multiline_string = """\ First line Second line Third line """ # or from inspect import cleandoc cleandoc(multiline_string) # 'First line\nSecond line\nThird line' By default, multiline strings in Python honor any indentation used in the string, therefore we need to use the ugly formatting shown in the first variable in the snippet above.
Find elsewhere
🌐
PyPI
pypi.org › project › textwrapper
textwrapper
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Top answer
1 of 9
128

You could use textwrap module:

>>> import textwrap
>>> strs = "In my project, I have a bunch of strings that are read in from a file. Most of them, when printed in the command console, exceed 80 characters in length and wrap around, looking ugly."
>>> print(textwrap.fill(strs, 20))
In my project, I
have a bunch of
strings that are
read in from a file.
Most of them, when
printed in the
command console,
exceed 80 characters
in length and wrap
around, looking
ugly.

help on textwrap.fill:

>>> textwrap.fill?

Definition: textwrap.fill(text, width=70, **kwargs)
Docstring:
Fill a single paragraph of text, returning a new string.

Reformat the single paragraph in 'text' to fit in lines of no more
than 'width' columns, and return a new string containing the entire
wrapped paragraph.  As with wrap(), tabs are expanded and other
whitespace characters converted to space.  See TextWrapper class for
available keyword args to customize wrapping behaviour.

Use regex if you don't want to merge a line into another line:

import re


strs = """In my project, I have a bunch of strings that are.
Read in from a file.
Most of them, when printed in the command console, exceed 80.
Characters in length and wrap around, looking ugly."""

print('\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', strs)))

# Reading a single line at once:
for x in strs.splitlines():
    print '\n'.join(line.strip() for line in re.findall(r'.{1,40}(?:\s+|$)', x))

output:

In my project, I have a bunch of strings
that are.
Read in from a file.
Most of them, when printed in the
command console, exceed 80.
Characters in length and wrap around,
looking ugly.
2 of 9
16

This is what the textwrap module is for. Try textwrap.fill(some_string, width=75).

🌐
Qinqianshan
qinqianshan.com › python › py_module › textwrap-text-package-and-fill
【2】文件读写-8-2-文本包装和填充--textwrap - Sam' Note
January 27, 2016 - import textwrap dedented_text =textwrap.dedent(sample_text).strip() print textwrap.fill(dedented_text,initial_indent='',subsequent_indent=' ' * 4,width=50,) The textwrap module can beused to format text for output in situations wherepretty-printing is desired.
🌐
YouTube
youtube.com › playlist
Python textwrap Module Tutorials - YouTube
Share your videos with friends, family, and the world
🌐
Python Morsels
pythonmorsels.com › wrapping-text
Wrapping text output in Python - Python Morsels
December 2, 2025 - Python's textwrap module includes utilities for wrapping text to a maximum line length.
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › textwrap.TextWrapper.wrap.html
textwrap.TextWrapper.wrap — Python Standard Library
Reformat the single paragraph in ‘text’ so it fits in lines of no more than ‘self.width’ columns, and return a list of wrapped lines. Tabs in ‘text’ are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space
🌐
Text Editor
texteditor.co
Text Editor - Free App for Editing Text Files
Text Editor can open all text files types including TXT, CSV, HTML, XML, CSS and JSON as well as code files such as C++, Java, and Python.
🌐
p5.js
p5js.org › reference
Reference
textWrap() Sets the style for wrapping text when text() is called. loadFont() Loads a font and creates a p5.Font object · text() Draws text to the canvas. textFont() Sets the font used by the text() function. font · The font's underlying ...
🌐
Medium
shafameidita.medium.com › enhancing-python-code-readability-with-textwrap-dedentation-cdf095b844c8
Enhancing Python Code Readability with textwrap.dedent() | by Shafa Salzabila Meidita | Medium
April 26, 2024 - textwrap is a built-in module in the Python programming language that provides functions for formatting text to fit a specified width. The textwrap module is commonly used for text formatting in text editors, document creation, or program output.
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)|
🌐
PyPI
pypi.org › project › textwrap3
textwrap3 · PyPI
textwrap from Python 3.6 backport (plus a few tweaks)
      » pip install textwrap3
    
Published   Jan 23, 2019
Version   0.9.2
🌐
Note.nkmk.me
note.nkmk.me › home › python
Wrap and Truncate a String with textwrap in Python | note.nkmk.me
January 28, 2024 - The textwrap.wrap() function splits a string into a list of segments, each fitting within the specified width. ... Specify the target string as the first argument, and the number of characters as the second argument (width).