Python Forum
How work with formatted text in Python? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How work with formatted text in Python? (/thread-16844.html)



How work with formatted text in Python? - AlekseyPython - Mar-17-2019

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?


RE: How work with formatted text in Python? - buran - Mar-17-2019

use triple quotes


RE: How work with formatted text in Python? - DeaD_EyE - Mar-17-2019

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.)



RE: How work with formatted text in Python? - AlekseyPython - Mar-18-2019

buran and DeaD_EyE, thanks!