Wrap long string in Python IDLE
Asked Answered
G

3

7

The string I am writing is very long. To make it easier to read, I would like to wrap the text onto multiple lines. How is this done?

Guay answered 17/5, 2018 at 4:35 Comment(4)
The content of the string doesn't have any relevance on the question. In the IDE for Python, the shell and the interactive sheet have the same problem. Put simply, if you type a very long piece of text, it disappears off the side of the page, unlike this comment box where it wraps the text around into many lines. If you use the return key to wrap the text, instead of starting a new line, it runs the program. Hoping someone knows how to wrap the text without executing the line of text.Guay
Are you talking about inputting a long line of text or outputting a long line of text? The answers are quite different for the two cases.Mckelvey
Hi. On the input side please. Most of the script is no longer than 40 characters however, the dictionary item is near 250 characters and very hard to edit as over half of it is off the page. ThanksGuay
Please show an example in your question. How to Ask and minimal reproducible exampleCoalition
V
1

Python allows you to split a long string in your source code into multiple substrings. Syntactically, adjacent string literals are simply concatenated; so "foo" "bar" is exactly equivalent to "foobar".

lorem_ipsum = (
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, "
    "sed do eiusmod tempor incididunt ut labore et "
    "dolore magna aliqua. Ut enim ad minim veniam, quis "
    "nostrud exercitation ullamco laboris nisi ut aliquip "
    "ex ea commodo consequat. Duis aute irure dolor in "
    "reprehenderit in voluptate velit esse cillum dolore "
    "eu fugiat nulla pariatur. Excepteur sint occaecat "
    "cupidatat non proident, sunt in culpa qui officia "
    "deserunt mollit anim id est laborum."
)

In IDLE, when you enter this, you'll see the ... prompt instead of the >>> prompt while you're in between the parentheses.

The parentheses aren't strictly necessary, either; you can backslash-escape newlines instead.

lorem_ipsum = \
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, " \
    "sed do eiusmod tempor incididunt ut labore et " \
    ...

If your string contains newlines, a triple-quoted string is the obvious choice.

lorem_ipsum = """\
Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
sed do eiusmod tempor incididunt ut labore et 
dolore magna aliqua. Ut enim ad minim veniam, quis 
nostrud exercitation ullamco laboris nisi ut aliquip 
ex ea commodo consequat. Duis aute irure dolor in 
reprehenderit in voluptate velit esse cillum dolore 
eu fugiat nulla pariatur. Excepteur sint occaecat 
cupidatat non proident, sunt in culpa qui officia 
deserunt mollit anim id est laborum."""

Here, the backslash after the opening """ escapes the newline so that it's not part of the string; the first characters are "Lorem ipsum". The newlines after "elit," "et" etc are part of the string, though.

To wrap strings you output, maybe look at the textwrap module in the standard library. If you like, you can obviously also use that to keep strings in your source code formatted in a manner which is convenient while editing - one common trick is to have indented multi-line strings in your source for visual consistency, but remove the indentation when you actually use the string:

from textwrap import dedent

if condition:
    while state:
        for elt in elements:
            paragraph = f"""\
                Convenient indented
                string with {condition}
                and {state} and {elt}""".dedent()
Vulpecula answered 11/8 at 12:17 Comment(0)
M
0

[This answer applies to Python in general and is not specific to IDLE.]

For input of long strings without embedded newlines, you could enter a multiline string and then delete the newlines. But if you want lines to end with spaces after commas and periods, you will not see them and they will disappear if you strip line-ending whitespace from your code. (This is required for CPython stdlib code.)

An alternative is to use Python's string literal concatenation feature. White space is guarded by line-ending quotes, and comments can be added. (See the link for another example.)

stories = {
    'John' : "One day John went to the store to buy a game.  "  # the lead
        "The name of the game was Super Blaster.  "  # the hint
        "On the way to the store, John was blasted by a purple ray.  "
        "The ray of purple light, mixed with super neutrinos, "
        "came from a alien spaceship hovering above."
    }

import textwrap
print('\n'.join(textwrap.wrap(stories['John'])))

# prints

One day John went to the store to buy a game.  The name of the game
was Super Blaster.  On the way to the store, John was blasted by a
purple ray.  The ray of purple light, mixed with super neutrinos, came
from a alien spaceship hovering above.
Mckelvey answered 20/5, 2018 at 16:57 Comment(2)
Hi all. I uncovered the correct method to manipulate the length of the input such as a dictionary in Python where the line length ii so far past the edge of the page width that you can do longer see the functions etc.Guay
To start a new line to keep the text compact. Use space, plus sign space and finally \ . The backslash will start a new lineGuay
P
-1
  1. Click on IDLE in the top left corner
  2. Select Settings
  3. Select Keys
  4. Locate 'newline-and-indent'
  5. Select Get New Keys for Selection
  6. Enter a shortkey of your choosing
Plow answered 6/2, 2023 at 0:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.