我在python中有一个多行字符串,我想替换它的特定行号。我有一个循环遍历每一行并将行号增加1,但当我到达需要替换的行时我该怎么办?有什么建议吗?
答案 0 :(得分:3)
yourstring = yourstring.split("\n")
yourstring[lineyouwant] = edit
yourstring = "\n".join(yourstring)
lineyouwant是0索引
答案 1 :(得分:1)
试试这个:
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)