+ 5
Storing long string inside a variable
Is there a way to store a long string inside a variable without resulting in ugly code? I used the continuous character "\", when the variable is printed it has undesired empty spaces. To remove the empty spaces I have to continue the string in root level, which result in ugly code, especially inside a function. https://code.sololearn.com/ci49rmL6nxER/?ref=app
16 Antworten
+ 9
Wong Hei Ming ,
some thoughts, maybe something like:
txt = '''\
This is a very long string and I want to put it in multiple \
lines when I'm typing with my text editor.'''
print(txt)
you could create the above text outside the function, at the top of the code, then give it as an argument to the function.
> using a left side indentation for your text when creating the variable will always result in unwanted spaces in the final output.
to avoid this you can do: (not very nice)
txt = 'hztg jutff hjzu7zg nbhzrfv hgzjko bhggzXX ' \
'juzh bgzjn jztf ftg56uj hftzjiik gftzhh gzzhjYY ' \
'end text'
print(txt)
or:
txt = ('hztg jutff hjzu7zg nbhzrfv hgzjko bhggzXX '
'juzh bgzjn jztf ftg56uj hftzjiik gftzhh gzzhjYY '
'end text')
an other way could be to store the text in a text file, each text in a separate line. then read the required line from the file and output it.
+ 3
Lothar
I find using the parenthesis to be the cleaner looking option.😎
+ 3
Lothar
I searched the web and found Bob_Li's maybe the solution I'm looking for.
Storing the string in a separate file is a good idea, which reminds me about Civilization 3 stores the text in xmls file, however it is not workable in the playground.
Storing the string outside of the function works with a small program.
However the little fun project I'm writing involves different functions, and many of them have to print something out to the screen. Therefore I prefer the string in stored inside related function for better management.
And this code maybe the solution, just to remember to add a space before the break.
https://code.sololearn.com/cr7gLylJG4MC/?ref=app
+ 2
Bob_Li
I tried your code and you may not believe it.
https://i.ibb.co/BLr7jsc/test-01.jpg
https://i.ibb.co/nkY8Dvf/test-02.jpg
+ 2
I made some progress and it "mostly" works.
Here is the code.
In short, I break it into small chunks and store them in a list.
Joining the elements with a space character before passing to wrapper and printed.
Funny thing is it decided not to join between line 18 and 19, 43 and 44.
https://code.sololearn.com/cbVP84B9Wadk/?ref=app
+ 2
Vitaly Sokol Tibor Santa
If working with textwrap, triple quotes will produce unexpected result when there are multiple paragraph in the string. Also it preserve the manual line break and highly possible print break a line in middle.
I put a long string in playground for fun.
It is annoying the website version doesn't wrap text while apps does.
+ 2
# In my opinion, you should just use triple quotes and write the text formatted exactly as you want it to appear, including hitting the left edge if you want. People will understand. That's what it's for. Aside from the indenting, it's the most readable way. It's also the easiest to write.
# That's Python. Go with it.
# You can surround it in parentheses to show the surrounding indentation.
pass
pass
pass
story = (
"""
Once upon a time,
they lived happily
ever after.
The End
"""
)
pass
print(story)
pass
pass
pass
+ 1
I have to un-mark my answer as best because I ran into another problem.
At first, I thought if I would find a solution to break a long string storing in a variable and keep it tidy, then I can work on top of it to add f-string and text wrapper or other fancy things later.
In this code if the wrap width is 60 or 70, second paragraph, which is after \n\n, is wrapping in an unexpected way.
https://code.sololearn.com/caEdaMMGypYB/?ref=app
Still an opening question...
+ 1
Wong Hei Ming
yes,it is inconsistent. Some width values preserves the \n\n, others delete it.
I found some discussions:
https://bugs.python.org/issue1859
my test
https://code.sololearn.com/cHT66CR3kcNM/?ref=app
+ 1
Bob_Li
The documentation suggested to use str.splitline or similar method if replace_whitespace=False.
My impression is that if using splitline method, the original string won't store inside a function, and the best place to store the string will be another text file, which will not work with playground.
If putting all the string at the root level, it is hard to tell where they will put because I want to format the string with variable at least.
Maybe I just have to accept ugly code in playground environment...
+ 1
I agree with Vitaly Sokol. Triple quotes is a good way to preserve formatting of text, without having to use control codes or weird line breaks. Having a long string in code, usually does not bother the linters and autoformatters, even if the line exceeds 80 characters, it displays nicely in a decent IDE or code editor. I think you are overthinking this. :)
https://ibb.co/cN30234
If you must put long bodies of text inside your code, I think this is usually already a design flaw, they should be stored externally in config files, localization files etc.
You can split the text along sentences, by using regular expressions, eg. re.findall()
0
Wong Hei Ming
textwrap good 😁.
you can also force line breaks, but it is sometimes not pretty where it break.
https://code.sololearn.com/c3qPvNxlA905/?ref=app
0
Wong Hei Ming wordwrap is easier with html and css.
Maybe just avoid \n\n.
Or just split your chunks into separate paragraphs and put them in a list.
0
Wong Hei Ming
after looking through the source code,
https://github.com/JUMP_LINK__&&__python__&&__JUMP_LINK/cpython/blob/3.12/Lib/textwrap.py
and doing some tests, I think adding:
drop_whitespace=False
to the wrap arguments fixes your missing \n\n problem
reading the source code lets you see what the module is doing under the hood. Luckily, this one is pure Python with some regex, so it was fairly readable.
Btw, the topic became "Wrapping long string to fixed linewidth in Python"😁.
When I first joined in, I thought it was about memory efficient way to store long strings in Python, then it was how to break long strings in code, and now it's textwrap. Fun topic.😎
my test:
https://code.sololearn.com/c44ay42H6s23/?ref=app
0
Wong Hei Ming
yes, that is chaotic behavior. 🤔.
The fact that width is influencing whitespace and newline handling seems like a design flaw.
just keep the drop_whitespace=False to keep it well behaved, just in case.
wow, you are stress testing this module...😅
0
Wong Hei Ming
feels like it's defeating the use of the module if it ends up with a lot of manual preprocessing.
you can make the string.format() and paragraph splitting dynamic to reduce the manual work. evaluate the .format first before splitting to paragraph list. This eventally creates static string list.
I used two lambda functions to do this and you only need to run the second one if x changes because the first one is embedded inside it.
The idea is to keep the DRY principle and avoid manual hardcoding.
https://code.sololearn.com/c9POR3Hq4XhN/?ref=app