user7872485
user7872485

Reputation:

Replace One Line of Multiline String In Python?

I have a multi-line string in python, and I want to replace a specific line number of it. I have a loop that goes through each line and increments the line number by 1, but what do I do when I reach the line I need to replace? Any suggestions?

Upvotes: 2

Views: 1683

Answers (2)

Abe
Abe

Reputation: 1415

Try this:

string = """line1
line2
line3
line4
line5"""
str_list = string.split('\n')
str_list[4] = "my new line value"
string = "\n".join(str_list)
print(string)

Upvotes: 1

Sam51
Sam51

Reputation: 251

yourstring = yourstring.split("\n")
yourstring[lineyouwant] = edit
yourstring = "\n".join(yourstring)

lineyouwant is 0 indexed

Upvotes: 5

Related Questions