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: sort individual lines in a multiline string

Is there a way to sort a multiline string alphabetically by individual line, while also keeping the output one multiline string?

Input string:

"First line.
A sentence here.
Other Line.
Different sentence."

Output string:

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

"A sentence here.
Different sentence.
First line.
Other Line."

>Solution :

You could split your multi-line string by newline (\n), then use the built-in sorted function, and reassemble the result into a multi-line string:

multi_line_str = """First line.
A sentence here.
Other Line.
Different sentence."""

"\n".join(sorted(multi_line_str.split("\n")))
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