Proper way to break up large strings

360 views Asked by At

I have to write an application that searches for some constant strings in a file/database (they haven't told me which it is yet, and it really doesn't matter for this post).
Anyway, these strings tend to be long (over 200 characters at times) and even with a fairly large monitor, this starts scrolling off the screen (well, I also have multiple windows open at once). Anyway, I would like to breakup the string for readability reasons, so I thought about triple-quoting the sucker with a bunch of newlines, but triple quoting keeps the newlines.
I suppose I could do

myStr = """some
           long
           string""".replace('\n', '')

But then I fear that they might one day require me to have newlines in myStr, so that's a bust. Even otherwise, the .replace(...) will have to be done every time the program runs, which is just not efficient. For the same reason, the following will also not work:

myStr = "some" + \
        "long" + \
        "string"

So I wonder what alternative ways there might be, to break up a really long string, keeping readability and code-efficiency in mind

Python 2.7 and 3.3 compatibility is a plus

3

There are 3 answers

2
James Mills On BEST ANSWER

I often do this in my code (which complies with PEP8):

my_long_string = (
    "foo"
    "bar"
    "baz"
)

print(my_long_string)

The parenthesis just evaluates the expression(s) into a single string.

4
BartoszKP On

It's an opinion-based topic, yet I'd like to propose a different solution: create a resource file with these strings, and reference them with readable key names.

Here you can find an example solution.

Another simplistic possibility is to just create a Python module with these resource strings:

resources.py

longString1 = "......."

longString2 = "......."

#...

And then use them in the code like resources.longString1. When they are separated in a separate file containing only resources there will be no problem with readability no matter what formatting you'll choose.

3
asdf On

If you're looking for alternate methods try this one:

string = "some long string"
string_list = string.split(' ') #The space here can be replaced with whatever you
                                #would like to split your string by may it be /n
                                #or whatever else. This method returns a list of
                                #strings.
'/n'.join(string_list) #This will rejoin your string back together with newlines
                       #where the spaces used to be. Again /n can be replaced