有没有一种方法可以按单行按字母顺序对多行字符串进行排序,同时保持输出为一个多行字符串?
输入字符串:
"First line.
A sentence here.
Other Line.
Different sentence."
输出字符串:
"A sentence here.
Different sentence.
First line.
Other Line."
您可以通过换行符 (
\n
) 拆分多行字符串,然后使用内置的 sorted
函数,并将结果重新组装为多行字符串:
multi_line_str = """First line.
A sentence here.
Other Line.
Different sentence."""
"\n".join(sorted(multi_line_str.split("\n")))