3

I have a long string:

S='Hello\n i have a very very very very..... very very very very.... long Text!'

Printing this text creates one long line and I would like to break the line into pieces with maximum lengths of 10 or 20 characters. I would like to break the line with \n and have the \n included in the new string.

What I'm hoping for:

Hello
i have a very 
very very very
..... very very 
very very.... 
long Text!
glennsl
  • 28,186
  • 12
  • 57
  • 75

3 Answers3

4

textwrap.wrap allows you to wrap strings to a certain width.

By default it replaces whitespace with single spaces, including newlines, before wrapping.

Set replace_whitespace=False if you want to keep newlines, etc.

>>> import textwrap
>>> s = 'Hello\n i have a very very very very..... very very very very.... long Text!'
>>> print('\n'.join(textwrap.wrap(s, width=20, replace_whitespace=False)))
Hello
 i have a very
very very very.....
very very very
very.... long Text!

The documentation for replace_whitespace:

(default: True) If true, after tab expansion but before wrapping, the wrap() method will replace each whitespace character with a single space. The whitespace characters replaced are as follows: tab, newline, vertical tab, formfeed, and carriage return ('\t\n\v\f\r').

Note If expand_tabs is false and replace_whitespace is true, each tab character will be replaced by a single space, which is not the same as tab expansion.

Note If replace_whitespace is false, newlines may appear in the middle of a line and cause strange output. For this reason, text should be split into paragraphs (using str.splitlines() or similar) which are wrapped separately.

Community
  • 1
  • 1
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
-3

You can use '''YOUR BIG STRING IN PARAGRAPH WHAT YOU WANT'''

Jay Parikh
  • 2,419
  • 17
  • 13
-4

You can also use double quotes instead of single if that is what you want.

s = """ this is a very
        long string if I had the
        energy to type more and more ..."""
Robert Jacobs
  • 3,266
  • 1
  • 20
  • 30