简体   繁体   English

在 python 中交换字符串的“行”

[英]Swapping “lines” of a string in python

I have a string that looks like this:我有一个看起来像这样的字符串:

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

This prints out:这打印出来:

Hello
Smith
Jake
I am

However, I would like it to be changed to this:但是,我希望将其更改为:

Hello
I am
Jake
Smith

Now some might say to just switch "I am" and "Smith" in your original string but the thing is I can't do that.现在有些人可能会说只需在原始字符串中切换“I am”和“Smith”,但问题是我不能这样做。 I need to look for another way to edit the string after.我需要寻找另一种方法来编辑字符串。

One clarification: "Smith" could be a different name and "I am" could also be another phrase like "You are".一个澄清:“史密斯”可能是一个不同的名字,“我是”也可能是另一个短语,如“你是”。 So lines 2 and 4 will not always be "Smith" and "I am" respectively.所以第 2 行和第 4 行并不总是分别是“Smith”和“I am”。

Another test case:另一个测试用例:

Original output:原装output:

Hi,
Doe?
John
Are you

Desired output:所需的 output:

Hi,
Are you
John
Doe?

Essentially I need something that can swap the fourth line of the string with the second line.本质上,我需要一些可以将字符串的第四行与第二行交换的东西。

Basically I've tried to split the string on '\n' into a list and then swap the values in the list and then rejoining the list with '\n' but it's really ugly.基本上,我尝试将 '\n' 上的字符串拆分为一个列表,然后交换列表中的值,然后用 '\n' 重新加入列表,但这真的很难看。 I am wondering if there is a better alternative.我想知道是否有更好的选择。

How about this?这个怎么样?

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

Or this?或这个?

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

Or this?或这个?

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

Or this?或这个?

>>> lines = string1.splitlines()
>>> lines[1], lines[3] = lines[3], lines[1]
>>> '\n'.join(lines)
'Hello\nI am\nJake\nSmith'
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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM