在python中交换字符串的 "行"。

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

我有一串像这样的东西。

string1 = "Hello" + '\n' + "Smith" +'\n'+ "Jake" +'\n'+ "I am"
print(string1)

这个可以打印出来

Hello
Smith
Jake
I am

但是,我想把它改成这样:

Hello
I am
Jake
Smith

有些人可能会说把 "I am "和 "Smith "换成原来的字符串 但问题是我不能这么做。我需要寻找另一种方法来编辑之后的字符串。

有一点需要说明的是。"Smith "可能是一个不同的名字 "I am "也可能是另一个短语,比如 "You are". 所以第2行和第4行不会一直分别是 "Smith "和 "I am"。

另一个测试案例。

原始输出:

Hi,
Doe?
John
Are you

理想的输出:

Hi,
Are you
John
Doe?

本质上,我需要一个能把字符串的第四行和第二行互换的东西。

基本上我试过将"\n "上的字符串分割成一个列表,然后交换列表中的值,然后用"\n "重新连接列表,但这真的很丑陋。我想知道是否有更好的选择。

python string
1个回答
2
投票

这个怎么样?

>>> one, two, three, four = string1.splitlines()
>>> '\n'.join((one, four, three, two))
'Hello\nI am\nJake\nSmith'

还是这个?

>>> lines = string1.splitlines()
>>> '\n'.join([lines[0], *reversed(lines[1:])])
'Hello\nI am\nJake\nSmith'

还是这个?

>>> lines = string1.splitlines()
>>> lines[1:] = reversed(lines[1:])
>>> '\n'.join(lines)
'Hello\nI am\nJake\nSmith'

或者这个?

>>> lines = string1.splitlines()
>>> lines[1], lines[3] = lines[3], lines[1]
>>> '\n'.join(lines)
'Hello\nI am\nJake\nSmith'

1
投票
string1 = "Hello" + '\n' + "Smith" +'\n'+ "Jake" +'\n'+ "I am"
phrases = string1.split("\n")
phrases[1], phrases[3] = phrases[3], phrases[1]
print("\n".join(phrases))
© www.soinside.com 2019 - 2024. All rights reserved.