pythonsorting

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:

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