Python Forum

Full Version: How work with formatted text in Python?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Python 3.7.2

I have a specially formatted text, that I just want to post to another site:
my_text = '\
var index_id = 0;\
var len = arr_id.length;\
while(index_id < len){\
    current_id = arr_id[index_id];\
    index_id = index_id + 1;\
    \
    offset = 0;\
    if (index_query == 0){\
        offset = initial_offset;\
    }\
}'
But if I form it as shown above, then it is a single string, that cann't be broken into substrings. And the code abounding with backslashes becomes very ugly.

Of course, I can save this text to a file and read it line by line, but I don't want to introduce unnecessary entities.

How to simply work with formatted text in Python?
use triple quotes
import textwrap


string_for_server = textwrap.dedent("""
    Your text
    In a Block
        4 spaces
        4 spaces
    """).lstrip()
Output:
Help on function dedent in module textwrap: dedent(text) Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form. Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines " hello" and "\thello" are considered to have no common leading whitespace. (This behaviour is new in Python 2.5; older versions of this module incorrectly expanded tabs before searching for common leading whitespace.)
buran and DeaD_EyE, thanks!