Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python newlines go away on splitting

I was trying to make a compression algorithm and a compressor that uses it in python.
While doing so, I saw that when compressing some example text, newlines are gone.
After some debugging, I found out that the split() function was removing the newlines.
I was converting a string to a list and a list to string so many times, but this time, the split() function removed all the newlines. If it would be a string:

i
hate foo
bar why do people use it what does it even mean

but after calling split(), it becomes:

['i', 'hate', 'foo', 'bar', 'why', 'do', 'people', 'use', 'it', 'what', 'does', 'it', 'even', 'mean']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

split() without argument given does split at any whitespaces, newline (\n) is one of whitespaces. If you want to split only at space characters, then provide " " as split 1st argument that is

text = '''i
hate foo
bar why do people use it what does it even mean'''
elements = text.split(" ")
print(elements)

output

['i\nhate', 'foo\nbar', 'why', 'do', 'people', 'use', 'it', 'what', 'does', 'it', 'even', 'mean']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading