2

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?

1
  • Can you show some code and data to illustrate your problem? Commented Sep 12, 2017 at 1:58

2 Answers 2

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

lineyouwant is 0 indexed

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.