Python:对多行字符串中的各个行进行排序

问题描述 投票:0回答:1

有没有一种方法可以按单行按字母顺序对多行字符串进行排序,同时保持输出为一个多行字符串?

输入字符串:

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

输出字符串:

"A sentence here.
Different sentence.
First line.
Other Line."
python sorting
1个回答
2
投票

您可以通过换行符 (

\n
) 拆分多行字符串,然后使用内置的
sorted
函数,并将结果重新组装为多行字符串:

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

"\n".join(sorted(multi_line_str.split("\n")))
© www.soinside.com 2019 - 2024. All rights reserved.