简体   繁体   中英

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 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.

Another test case:

Original output:

Hi,
Doe?
John
Are you

Desired 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. 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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