Reputation:
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
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
Reputation: 251
yourstring = yourstring.split("\n")
yourstring[lineyouwant] = edit
yourstring = "\n".join(yourstring)
lineyouwant is 0 indexed
Upvotes: 5